【问题标题】:mouse event problem with nested elements嵌套元素的鼠标事件问题
【发布时间】:2009-11-27 11:41:56
【问题描述】:

我有类似以下内容:

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

问题在于,如果您将鼠标放在 img 上,则 div 点击会在鼠标向上时触发。我试图通过将onclick="return false;" 添加到 img 元素来覆盖 div onclick,但 div onclick 仍在触发。我还有一个取消气泡并在文档 onmouseup 事件中返回 false(它在 img ondown 事件中动态附加)。

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

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    cancelBubble 已弃用。

    在图片的onclick事件中使用event.stopPropagation()代替cancelBubble【非标准方法】。

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

    【讨论】:

    • IE 不支持 stopPropagation... 我想我应该在 IE 中使用 cancelBubble?
    【解决方案2】:

    考虑使用像 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>
    

    【讨论】: