jquery hover事件如何不冒泡
每个div鼠标经过时div背景颜色变化,但不想让镶嵌的div的父div变色,如何做?
听说是什么冒泡事件,不懂。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> function div_hover(){ $("div").hover( function(){ $(this).addClass("hover"); }, function(){ $(this).removeClass("hover"); } ); } $(function(){ div_hover(); }); </script> <style type="text/css"> .box1{background:green;width:400px;height:400px;} .box2{background:yellow;width:300px;height:300px;} .box3{background:#cc3333;width:200px;height:200px;} .hover{background:#33cc33} </style> <div class="box1"> <div class="box2"> <div class="box3"></div> </div> </div>
$("div").hover( function(e){ $(this).addClass("hover"); e.stopPropagation(); //这里 }, function(e){ $(this).removeClass("hover"); e.stopPropagation(); //这里 } );
e.stopPropagation(); 直接放进去没效果嘛?忘2楼给个运行版看看
结果出来了,很复杂
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> function div_hover(){ var levels = {}; var min = 100, max = 0; var change = function() { var q = 0; for (var p in levels) { $(levels[p]).removeClass("hover"); q = Math.max(q, p); } $(levels[q]).addClass("hover"); }; var getLevel = function(element) { var level = 0; for (var parent = element; parent.parentNode; parent = parent.parentNode) level++; return level; }; $("div").hover( function(){ levels[getLevel(this)] = this; change(); }, function(){ delete levels[getLevel(this)]; $(this).removeClass("hover"); change(); } ); } $(function(){ div_hover(); }); </script> <style type="text/css"> .box1{background:green;width:400px;height:400px;} .box2{background:yellow;width:300px;height:300px;} .box3{background:#cc3333;width:200px;height:200px;} .hover{background:#33cc33} </style> <div class="box1"> <div class="box2"> <div class="box3"></div> </div> </div>
没有使用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> <title></title> <style type="text/css"> .box1{background:green;width:400px;height:400px;} .box2{background:yellow;width:300px;height:300px;} .box3{background:#cc3333;width:200px;height:200px;} .hover{background:#33cc33} </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { $("div").mouseover(function(e) { $(this).addClass("hover"); e.stopPropagation(); }); $("div").mouseout(function(e) { $(this).removeClass("hover"); e.stopPropagation(); }); }); </script> </head> <body> <div class="box1"> <div class="box2"> <div class="box3"></div> </div> </div> </body> </html>
哈哈,三个效果都不一样。有意思。
以上是jquery:hover事件为何不冒泡?的详细内容。更多信息请关注PHP中文网其他相关文章!