点击span时不让li触发active,只触发span的active



 <!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
               ul {
                   list-style-type: none;
                   margin: 0;
                   padding: 0;
               }
               li:active {
                   background-color: darkgrey;
               }
               #text:active{
                   opacity: 0.5;
               }
        </style>        
    </head>
    <body>
        <ul>
            <li>
                <img src="http://dcloudio.github.io/mui/assets/img/cbd.jpg" width="100" height="100"/>
                <span id="text">
                         查看详情
                </span>
            </li>
        </ul>
    </body>
</html>

css htm JavaScript

邻人四十二 9 years, 11 months ago

同时也会触发 <li> 是因为事件冒泡,阻止事件冒泡即可。


 var span = document.getElementById('text');
span.onclick = function (e) {
    if (e.stopPropagation) {
       e.stopPropagation(); // 阻止事件冒泡
    }
    else {
        e.cancelBubble = true; // IE8及之前版本,阻止事件冒泡
    } 
    // do something
}

resrt answered 9 years, 11 months ago

Your Answer