English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JQueryを使用してDIVの選択を実現する方法

我们设置4个div 当鼠标移动到某一个div上面的时候 背景颜色就会发生变化

那我们应该知道要用到mouseover() 和 mouseout() 前一个是移动到某个位置 后面是移开某个位置

还有一个hover(,) 可以替代上面两个方法

1.用mouseover()和mouseout()

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv-equiv="Content-Type-Type" content="text/html; charset=utf-8/html; charset=utf-8-8" />
<script type="text/javascript" src="jQuery/jquery-1.12.1.js"></script>
<script type="text/javascript">
$("function(){

	$("div[id^='div']").mouseover(function() {
    $("this").css("background-color","red");
    //$("this").css({"background-color":"red"});
 });
	$("div[id^='div']").mouseout(function() {
    $("this").css("background-color","#0FC");
    //$("this").css({"background-color":"#0FC"});
 });
});
</script>
<style type="text/css">
div[id^="div"]
{
	width:300px;
	height:500px;
	background-color:#0FC;
	border:1px solid black;
	float:left;
	margin-left:2px;
}
</style>
</head>
<body>
<div id="div1></div>
<div id="div2></div>
<div id="div3></div>
<div id="div4></div>
</body>
</html>

2.hover()

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv-equiv="Content-Type-Type" content="text/html; charset=utf-8/html; charset=utf-8-8" />
<script type="text/javascript" src="jQuery/jquery-1.12.1.js"></script>
<script type="text/javascript">
$("function(){

	$("div[id^='div']").hover(function(){
		$("this").css("background-color","blue");
		},
		function(){
			$("this").css("background-color","#0FC");
	});
});
</script>
<style type="text/css">
div[id^="div"]
{
	width:300px;
	height:500px;
	background-color:#0FC;
	border:1px solid black;
	float:left;
	margin-left:2px;
}
</style>
</head>
<body>
<div id="div1></div>
<div id="div2></div>
<div id="div3></div>
<div id="div4></div>
</body>
</html>

もしくはこんな感じで

$("function(){

	var In = function(){
		$("this").css("background-color","red");
	}
	var Out = function(){
		$("this").css("background-color","yellow");
	}
	$("p[id^='p']").hover(In,Out);	
});

以上のこのjQueryでDIVの選択を実現する方法が、編集者が皆さんに提供する全ての内容です。皆さんに参考になれば幸いですし、もっと応援していただければと思います。

おすすめ