为什么trigger()无法触发hover事件

快乐打工仔 分类:实例代码

使用trigger()方法可以触发事件,具体可以参阅jQuery trigger()一章节。

但是使用trigger()却无法触发hover事件,下面先看一段代码实例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style type="text/css">
#antzone{
  width:100px;
  height:100px;
  background:red;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(document).ready(function(){
  $("#antzone").hover(function(){
    $(this).css("background-color","green");
  },function(){
    $(this).css("background-color","red");
  })
  $("#antzone").trigger("hover");
});
</script>
</head>
<body>
<div id="antzone"></div>
</body>
</html>

上面的代码并没有出发hover事件。

其实也是可以理解的,hover事件具有两种行为,你说触发到底执行哪个好呢。

在jQuery中hover事件是由mouseenter事件和mouseleave事件综合而成,所以你要单独出发才行,代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style type="text/css">
#antzone{
  width:100px;
  height:100px;
  background:red;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(document).ready(function(){
  $("#antzone").hover(function(){
    $(this).css("background-color","green");
  },function(){
    $(this).css("background-color","red");
  })
  $("#antzone").trigger("mouseenter");
});
</script>
</head>
<body>
<div id="antzone"></div>
</body>
</html>

回复

我来回复
  • 暂无回复内容