示例:定义一个div,默认为蓝色,当鼠标滑到此处时,变成红色
写法1:使用mouseover和mouseout事件
<html>
<head>
<meta http-equiv="Content-Type content="text/html;charset=gbk" />
<style type="text/css">
div[id^="div"]
{
width:200px;
height:200px;
border:1px solid black;
background-color:blue;
float:left;
margin-left:5px;
}
</style>
<script type="text/javascript" src="jslib/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(function(){
$("div[id^='div']").mouseover(function(){
$(this).css("background-color","red");
});
$("div[id^='div']").mouseout(function(){
$(this).css("background-color","blue");
});
});
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
</body>
</html>
执行结果
方法2:使用hover事件
“#(document).ready()省略成$();”
<html>
<head>
<meta http-equiv="Content-Type content="text/html;charset=gbk" />
<style type="text/css">
div[id^="div"]
{
width:200px;
height:200px;
border:1px solid black;
background-color:blue;
float:left;
margin-left:5px;
}
</style>
<script type="text/javascript" src="jslib/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
$("div[id^='div']").hover(function(e){
$(this).css("background-color","yellow");
},function(e){
$(this).css("background-color","blue");
});
});
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
</body>
</html>
执行结果
网友评论