js实现鼠标悬浮元素出现/隐藏效果

参考慕课网视频:https://www.imooc.com/video/2879

实现效果比较简单,实现方法也不难,但有些细节需要注意。

  • 最终效果如图:

鼠标移到“分享”上方时,粉红色div缓慢出现:

鼠标移开时,自动缓慢隐藏

  • 实现思路:

首先是给div定义一个left,且值为负数,使之隐藏。通过js鼠标事件,使用定时器,改变left的值。

  • 实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js鼠标悬浮缓慢出现动画</title>
    <style type="text/css">
        *{
            margin: 0;
        }
        #div1{
            width: 200px;
            height: 200px;
            background: lightpink;
            position: relative;
            left: -200px;
            top: 0px;
        }
        #share{
            width: 50px;
            height: 50px;
            line-height: 50px;
            text-align: center;
            color: aliceblue;
            background: darkgray;
            position: absolute;
            left: 200px;
            top: 75px;
        }
    </style>
</head>
<body>
    <div id="div1">
        <span id="share">分享</span>
    </div>
</body>
<script>
    window.onload = function () {
        var div1 = document.getElementById('div1');
        div1.onmouseover = function () {
            startMove(0);
        }
        div1.onmouseout = function () {
            startMove(-200);
        }
    }

    var timer = null;
    function startMove(iTarget) {
        //clearInterval清除定时器,因为鼠标每对元素操作一次就会触发一次startMove函数,开启一个定时器,如果不清除,可能存在同时启动多个定时器的情况,使得元素移动速度变快。
        clearInterval(timer);
        var div1 = document.getElementById('div1');
        timer = setInterval(function () {
            var speed = 1;
            if (div1.offsetLeft > iTarget) {
                speed = -1;
            }
            if (div1.offsetLeft == iTarget) {
                clearInterval(tiemr);
            }
            div1.style.left = div1.offsetLeft + speed * 10 +'px';
        },30)
    }

</script>
</html>

猜你喜欢

转载自blog.csdn.net/code_5/article/details/84819387