javascript - Js改变元素透明度函数,关于变量的作用域问题?
ringa_lee
ringa_lee 2017-04-11 12:11:04
[JavaScript讨论组]

写了一个变换透明度的函数,但是作用域有问题,甚至很奇怪。。。
代码:




    
    Document
    


    

为什么在我这个函数里,只有在外部定义一个值才有效?而且在外部用box.style.opacity(和想赋的值相同)赋值都不行,只能用一个数值;在函数内部用 box.style.opacity 赋值也不应该没有效果啊??

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
PHP中文网
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        #box{
            width: 800px;
            height: 800px;
            background-color: #1AE2F6;
        }
    </style>
</head>
<body>
    <p id="box"></p>
    <script>
        var box = document.getElementById("box");
        box.style.opacity = 0.1;
        box.onmouseover = function() {
            changeopto(1);
        }
        box.onmouseout = function() {
            changeopto(0.1);
        }
        var timer = null;
        function changeopto(newOp) {
            clearInterval(timer);
            timer = setInterval( function() {
                var cgspeed = 0;//每个时间单位变换的值
                alpha = Number(box.style.opacity)
                console.log(box.style.opacity);
                if (newOp < alpha){
                     cgspeed = -0.01;
                     alpha += cgspeed;
                     box.style.opacity = alpha;
                }
                if (newOp > alpha){
                     cgspeed = 0.01;
                     alpha += cgspeed;
                     box.style.opacity = alpha;                
                }
                if (newOp == alpha){
                    clearInterval(timer);
                }
            } , 10 );    
        }
    </script>
</body>
</html>
PHPz

因为你不能用 +
box.style.opacity 返回值是字符串,所以如果 box.style.opacity += 0.1 得到的是"0.10.1"显然不合法。
alpha=box.style.opacity;也一样, 这样alpha也是字符串了。
所以要

// function toNumber(v) { return +v;}
alpha = +box.style.opacity;
// or
box.style.opacity = +box.style.opacity + 0.1;

P.S. 如果没有内联样式body.style.opacity === ""

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号