JS 实现鼠标移入移出透明度动画变化效果

代码:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 300px;
            height: 300px;
            background-color: #06c;
            opacity: 0.3
        }
    </style>
</head>

<body>
    <div></div>

    <script>
        //当鼠标移入div的时候  让div的透明度  动画变成1  鼠标移出div  透明度动画变回0.3
        //1.获取元素
        var div = document.getElementsByTagName("div")[0];
        var timer1 = null;
        var timer2 = null;

        //2.给div 添加事件
        div.onmouseover = function () {
            clearInterval(timer1);
            clearInterval(timer2);
            //透明度 ---> 1
            //1.设置动画三要素
            var start = getStyle(div, "opacity") * 1;
            var end = 1;
            var step = 0.01;
            //2.设置定时器
            timer1 = setInterval(function () {
                //走一步的代码
                //更新起点
                start += step;
                if (start >= end) {
                    clearInterval(timer1);
                    start = end;
                }
                //设置样式
                div.style.opacity = start;
            }, 20)
        }

        div.onmouseout = function () {
            //透明度 --->0.3
            clearInterval(timer1);
            clearInterval(timer2);
            //透明度 ---> 0.3
            //1.设置动画三要素
            var start = getStyle(div, "opacity") * 1;
            var end = 0.3;
            var step = 0.01;
            //2.设置定时器
            timer2 = setInterval(function () {
                //走一步的代码
                //更新起点
                start -= step;
                if (start <= end) {
                    clearInterval(timer2);
                    start = end;
                }
                //设置样式
                div.style.opacity = start;
            }, 20)
        }

        function getStyle(ele, prop) {
            //1.编写主要代码
            //如果 元素.currentStyle == undefined  标准浏览器中
            if (ele.currentStyle == undefined) {
                //为了让 别人 在函数外面 也能得到我们获取的属性值 我们要把属性值返回出来
                return getComputedStyle(ele)[prop];
            } else {
                return ele.currentStyle[prop];
            }
            //2.分析不确定的值 提取出来 作为参数  元素 属性
            //3.将参数带入到 函数中
        }
    </script>
</body>

</html>

 

posted @ 2020-09-17 09:36  石海莹  阅读(956)  评论(0编辑  收藏  举报