点击某个元素及点击某个元素之外的地方

  • 点击某个元素及点击某个元素之外的地方
<!DOCTYPE html>
<html>
    <style>
        .left {
            width: 100px;
            height: 200px;
            background: red;
            float: left;
        }
        .right {
            height: 300px;
            background-color: blue;
            overflow: hidden;
        }
    </style>
    <body>
        <div>
            <div class="left">
                <p id="myElement">left-p</p>
            </div>
            <div class="right">right</div>
        </div>
        <script type="text/javascript">
            document.addEventListener('click', function(evt) {
                const ele = document.getElementById('myElement');
                console.log('ele: ', ele);
                // isClickedOutside 为 true 如果点击的元素在 ele 之外
                const isClickedOutside = !ele.contains(evt.target)
                console.log('isClickedOutside:', isClickedOutside)
            })
        </script>
    </body>
    
</html>
posted @ 2024-07-30 22:59  安静的嘶吼  阅读(6)  评论(0编辑  收藏  举报