美文网首页
javascript 淡入淡出效果

javascript 淡入淡出效果

作者: 何必自找失落_ | 来源:发表于2016-12-07 11:40 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>鼠标移入移出改变透明度</title>
        <link rel="stylesheet" type="text/css" href="css/reset.css">
        <style type="text/css">
            body{
                text-align: center;
                margin-top: 20px;
            }
        </style>
    </head>
    <body>
        <img src="xxx.jpg" id="img">
        <script type="text/javascript">
            window.onload = function (){
                var img = document.getElementById("img");
                img.onmouseover = function (){
                    fade(this,30);
                }
                img.onmouseout = function(){
                    fade(this,100);
                }
                // 获得属性例如width  opacity 是特殊情况 不适用与本例子
                // function css(ele,pro){
                //  if (ele.currentStyle) {
                //      return ele.currentStyle[pro];
                //  }else{
                //      return getComputedStyle(ele, false)[pro];
                //  }
                // }
                function fade(ele,target){
                    clearInterval(ele.timer);
                    ele.timer = setInterval(function (){
                        //下面的三行代码确定 浏览器是否支持 opacity 
                        var div = document.createElement("div");
                        div.setAttribute("style","opacity : 0.5");
                        var isOpacity = div.style.opacity === "0.5";
    
                        if (isOpacity) {
                            // 也可以用css函数
                            // var now = css(ele,"opacity")*100;
                            var now = ele.style.opacity*100;
                        }else{
                            //不支持opacity 使用filter 
                            var mow = ele.style.filter.match(/opacity=(\d+)\)$/)[1]
                        }
                        var speed = (target - now)/5;
                        //根据速度 选择向上取整或者向下取整
                        speed = speed>0?Math.ceil(speed):Math.floor(speed);
                        now+=speed;
                        ele.style.opacity = now/100;
                        ele.style.filter = "alpha(opacity="+now+")";
                        if (now == target) {
                            clearInterval(ele.timer);
                        }
                    },30)
                }
            }
        </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:javascript 淡入淡出效果

          本文链接:https://www.haomeiwen.com/subject/xhpdmttx.html