当鼠标进入时动态创建的元素。(意外触发鼠标输出事件)
我想要有工具栏,从具有类container
div中检测mouse-out / in事件。 mouseover
和mouseout
事件正在按预期工作。 当鼠标移入和移出元素及其后代时,会触发这些事件。 但是有一些事情是不可预料的:当鼠标移动时,新创建的div被移除。移除后它将触发mouseover
事件,因此创建了另一个新的div。这使它变得令人眼花缭乱。 任何遇到过这种问题的人请帮助我。 谢谢。
假设你有这个HTML:
而且,这个JavaScript:
$(function() { $('div.container').on('mouseover', function(e){ e.stopPropagation(); $(this).append("") console.log("into " +$(this).attr('id')); }).on('mouseout', function(e){ $(".newdiv",this).remove(); console.log("out from " + $(this).attr('id')); }) });
使用CSS:
.parent { border:1px solid black; width:100%; height:400px; } .child { float:left; width:40%; border:1px solid red; margin:1px; height:300px; } .newdiv{ border:1px solid blue; margin:2px; width:100px; height:100px; position:absolute; right:0; }
我发现了这个问题,它出现在你的CSS中。 添加相对位置。 否则它假设第一个具有相对位置。
.child { float:left; width:40%; border:1px solid red; margin:1px; height:300px; position: relative; }
看看http://jsfiddle.net/Jn7e2/
你和你的追加函数后面没有分号。 这将克服任何其他问题。
也许您需要使用show()和hide()来聚焦div,因为从子传播到父级的事件可能存在问题。 那这个呢:
- JS:
$(function(){ $('div.container')。on('mouseover',function(e){ e.stopPropagation(); $(本)。儿童( “newdiv。”)显示()。 console.log(“into”+ $(this).attr('id')); })。on('mouseout',function(e){ e.stopPropagation(); $( “newdiv。”,这一点).hide(); console.log(“out from”+ $(this).attr('id')); }) });
所有,我确实找到了一种方法来制作它,但它非常冗长,看起来很丑陋……任何人都可以提供更好的方法来让它变得更容易和有趣..希望如此。 谢谢。
$(function() { $('div.container').mouseenter(function(e){ e.stopPropagation(); $(this).css("border","2px solid red"); $(this).append(""); $(this).parents().each(function(){ if ($(this).children(".newdiv").length>0) { $(this).children(".newdiv").remove(); $(this).css("border","1px solid red"); } }); if ($(".newdiv",this).length==0) { //alert('ddd'); } console.log("into " +$(this).attr('id')); }).mouseleave( function(e){ $(".newdiv",this).remove(); if ($(this).parent().hasClass("container") && $(".newdiv",$(this).parent()).length==0) { $(this).parent().css("border","2px solid red"); $(this).parent().append(""); } $(this).css("border","1px solid red"); console.log("out from " + $(this).attr('id')); }); });