如何:将Div设置为链接,而不是其中的图像

How to: Make a Div a link, but not the images within it

本文关键字:图像 Div 设置 链接 如何      更新时间:2023-09-26

很抱歉就同样的场景问了更多的问题,但这里是:

我的文本很棒,图像放置得很完美,但是,我不希望jquery滑动方法在图像被点击时运行(那些保存用于其他功能)。是否有可能使幻灯片功能仅在单击图像左侧的"块"时运行?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script> 
$(document).ready(function(){
  $("#flip").click(function(){
    $("#panel").slideToggle("slow");
  });
});
</script>
<body>
    <div id="flip">
        <div id="flipBox"><p>Click to slide the panel down or up</p></div>
        <img class="ux" src="http://placekitten.com/32/32" alt="complete" height="32" width="32" align="right" />
        <img class="ux" src="http://placekitten.com/32/32" alt="add" height="32" width="32" align="right" />
        <img class="ux" src="http://placekitten.com/32/32" alt="edit" height="32" width="32" align="right" />
        <img class="ux" src="http://placekitten.com/32/32" alt="remove" height="32"     width="32" align="right" />
    </div>
    <div id="panel">Hello world!</div>
</body>

这里是jfiddle的链接:http://jsfiddle.net/rvAPk/

我非常感谢SO的知识渊博的人!谢谢你们了!

aj

您可以使用 e.stopPropagation () :

防止事件冒泡到DOM树,防止任何父处理程序无法收到事件通知。

$("#flip img").click(function(e){
    e.stopPropagation()
});

更新小提琴

或者你可以试试这个:

<script> 
$(document).ready(function(){
  $("#flip").click(function(e){
    if(!($(e.target).is(".ux"))) {
      $("#panel").slideToggle("slow");
    }
  });
});
</script>

我在Android浏览器的实际开发中遇到过event. stoppropagation()不工作的一些原因,我采用了与上面相同的方法,即检查事件目标。

按照您的示例,您可以这样做…

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script> 
$(document).ready(function(){
  $("#flip").click(function(e){
    if($(e.target).prop("tagName") == 'IMG')
    return false;    
    $("#panel").slideToggle("slow");
  });
});
</script>
<body>
    <div id="flip">
        <div id="flipBox"><p>Click to slide the panel down or up</p></div>
        <img class="ux" src="http://placekitten.com/32/32" alt="complete" height="32" width="32" align="right" />
        <img class="ux" src="http://placekitten.com/32/32" alt="add" height="32" width="32" align="right" />
        <img class="ux" src="http://placekitten.com/32/32" alt="edit" height="32" width="32" align="right" />
        <img class="ux" src="http://placekitten.com/32/32" alt="remove" height="32"     width="32" align="right" />
    </div>
    <div id="panel">Hello world!</div>
</body>