Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

添加position属性导致mouseenter事件出现bug,为什么?

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title></title>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    #box {
        width: 800px;height: 300px;
        border:1px black solid;
        margin: 20px auto;
        position: relative;
    }
    li{list-style: none;}
    .ulTitle {
        width: 200px;height: 200px;
        position: absolute;
        left: 50px;top: 50px;
    }
    .ulTitle li {
        width: 50px;height: 50px;
        background-color: blanchedalmond;
        font-family:'微软雅黑';
        font-size: 8px;
        text-align: center;
        line-height: 50px;
        cursor: pointer;
    }
    .ulTitle .target {
        background-color: rgb(145, 199, 84);
        .ulImg li{
            display: none;
        }
        .ulImg .show {
            display: block;
        }
    </style>
    <script src="jquery-3.5.1.js"></script>
    <script>
        $(function () {
             // 1 监听移入事件
            $('.ulTitle li').mouseenter(function(){
                // 1.1 为移入的当前li添加上ulTitle target类,并取消其他同级元素的此类
                $(this).addClass('ulTitle target')
                $(this).siblings().removeClass('ulTitle target');
                // 1.2 获取所移入li的索引
                var $index = $(this).index();
                // 1.3 获取需展示的图片
                var $img = $('.ulImg li').eq($index);
                // 1.4 展示目标图片,并隐藏其他图片
                $img.addClass('ulImg show');
                $img.siblings().removeClass('ulImg show')
            })




        });
        // 该练习出现bug,为ul添加position属性后,鼠标移入事件高频次多次执行。不会修改。
    </script>
</head>
<body>
    <div id="box">
        <ul class="ulTitle">
            <li class="target">保管箱</li>
            <li>手机</li>
            <li>手环</li>
            <li>电视</li>
        </ul>
        <ul class="ulImg">
            <li class="show"><img src="/2原生动画/img/111.png" alt="" srcset=""></li>
            <li><img src="/2原生动画/img/222.png" alt="" srcset=""></li>
            <li><img src="/2原生动画/img/333.png" alt="" srcset=""></li>
            <li><img src="/2原生动画/img/444.png" alt="" srcset=""></li>
        </ul>
    </div>
</body>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

把ul的class附加到li上,导致样式异常

// 原来
$(this).addClass('ulTitle target')
$(this).siblings().removeClass('ulTitle target');

// 修改后

$(this).addClass('target')
$(this).siblings().removeClass('target');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...