【问题标题】:Javascript element.style.opacity is undefined. Why?Javascript element.style.opacity 未定义。为什么?
【发布时间】:2015-03-02 04:56:57
【问题描述】:

我正在尝试制作一个闪烁元素的 JS 函数。我使用setInterval() 进行计时,但它给出了错误消息Uncaught TypeError: Cannot read property 'opacity' of undefined

当我尝试不使用计时器而是“手动”修改不透明度时,它会起作用...

我做错了什么?

用法:

document.getElementById('idOfTheElement').startFlicker();

功能:

Element.prototype.startFlicker = function() {
    var blinkInterval = setInterval(function() {
        if (parseInt(this.style.opacity) === 0) {
            this.style.opacity = 1;
        } else {
            this.style.opacity = 0;
        }
    }, 50);
};

【问题讨论】:

  • 您的this 不是您想的那样。在区间内超出范围

标签: javascript element setinterval opacity


【解决方案1】:

你总是可以引用元素本身,因为在 setInterval 函数中,窗口对象被传递为this

相反,您应该尝试.bind()。所以this 将是对方法参数的引用。

Element.prototype.startFlicker = function() {
    var blinkInterval = setInterval(function() {
        if (parseInt(this.style.opacity) === 0) {
            this.style.opacity = 1;
        } else {
            this.style.opacity = 0;
        }
    }.bind(this), 50);
};

【讨论】:

    【解决方案2】:

    试试这个

    Element.prototype.startFlicker = function() {
        var self = this;
    
        var blinkInterval = setInterval(function() {
            if (parseInt(self.style.opacity) === 0) {
                self.style.opacity = 1;
            } else {
                self.style.opacity = 0;
            }
        }, 50);
    };
    

    setInterval this 指的是window,您需要在变量中存储上下文(this - 当前元素)并在setInterval 中使用

    【讨论】:

      【解决方案3】:

      因为上下文。 setInterval 内的this.style 指的是全局window 对象。

      【讨论】:

        猜你喜欢
        • 2021-12-30
        • 2021-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-10
        • 2012-01-10
        • 2012-09-30
        • 1970-01-01
        相关资源
        最近更新 更多