2009-11-27 97 views
0

我有类似下面的内容:鼠标事件问题嵌套元素

<div onclick="divClickEvent();"> 
    <img onmousedown="imgOnDownEvent();" /> 
</div> 

的问题是,如果你的鼠标下的IMG,在鼠标弹起股利点击火灾。我试图通过向img元素添加一个onclick="return false;"来覆盖div onclick,但div onclick仍然在触发。我也有一个取消泡泡,并在文档onmouseup事件(它在img ondown事件中动态附加)返回false。

我已经用完了想法。为什么div仍在处理该事件,我该如何阻止它?

回答

1

cancelBubble已弃用。

使用event.stopPropagation()代替图像的onclick事件中的cancelBubble [非标准方法]。

它阻止当前事件的进一步传播。

+0

是的,这是固定不变的它的感谢! – fearofawhackplanet 2009-11-27 11:55:42

+1

IE不支持stopPropagation ...我假设我应该在IE中使用cancelBubble? – fearofawhackplanet 2009-11-27 13:14:15

1

考虑使用抽象的框架如jQuery,在那里你可以用同样的方法停止传播不管浏览器版本:

<div id="image_holder"> 
    <img id="some_image" alt="" src="" /> 
</div> 

<script type="text/javascript"> 
    $(document).ready(function(){ // This will be run when DOM is ready 
      var holder = $('#image_holder'), 
       someImage = $('#some_image'); 

      someImage.bind('mousedown', function(event){ 
       // This will be run on mousedown 
       event.preventDefault().stopPropagation(); 
      }); 
    }); 
</script>