2013-02-22 68 views
0
  • 我所有的元素绝对定位
  • ITEM2的执行事件包含在物品1
  • 当我点击ITEM2,默认行为是执行的ITEM2,然后点击点击项目1
  • 我可以以某种方式阻止任何在item1上执行的动作,当我点击item2时?

请点击ITEM2在拨弄防止含有元素时,子元素上点击

我的小提琴:

http://jsfiddle.net/z9Unk/59/

HTML

<div class="item1"> 
    item1 
</div> 
<div class="item2"> 
    item2 
</div> 
<div class="item3"> 
    item3 
</div> 

CSS:

item1 { 
    position:absolute; 
    width:150px; 
    height:150px; 
    background-color:red; 
    top:5%; 
} 

.item3, .item2 { 
    position:absolute; 
    width:50px; 
    height:50px; 
    background-color:green; 
    top:8%; 
    left:1%; 
    display:none; 
} 

.item3 { 
    top:18%; 
} 

JS:

var item1 = $(".item1"); 
var item2 = $(".item2"); 
var item3 = $(".item3"); 

item1.hover(
    function() { 
     item2.show(); 
     item3.show(); 
    }, 
    function() { 
     item2.hide(); 
     item3.hide(); 
    } 

); 

item2.hover(
    function() { 
     item3.hide(); 
    }, 
    function() { 
    } 

); 

item2.click(
    function() { 
     alert("Perform some function"); 
    } 
); 

item1.click(
    function() { 
     alert("Perform item1 function"); 
    } 
); 
+0

的http://的jsfiddle。 net/z9Unk/60/- > e.stopPropagation() – banzomaikaka 2013-02-22 02:05:57

+0

which is preferren e.stop()or return false ???非常感谢 – 2013-02-22 02:08:06

+0

返回false似乎做我想要的东西... e.stopPropagatio()没有...让我测试更多 – 2013-02-22 02:11:44

回答

1

简单地返回false:

item2.click(
    function() { 
     alert("Perform some function"); 
     return false; 
    } 
); 

item1.click(
    function() { 
     alert("Perform item1 function"); 
     return false; 
    } 
); 

阅读:What does "return false;" do?

1

可以向上冒泡DOM树,阻止任何父处理程序被通知的阻止事件事件。

DOM Level 3的活动:stopPropagation

IE6-8您可以在事件处理程序添加return falsewindow.event.cancelBubble = true如果你使用jquery

,可以在所有浏览器中使用event.stopPropagation