2

这可能是一个愚蠢的问题,但我无法让这个超级简单的脚本工作。我需要一个可以将不透明度降低 0.1 的按钮。每次点击它。

我已经尝试了所有这些。

x.style.opacity-.3; //This doesn't work. Doesn't do anything.
x.style.opacity=.3; //This gives me an opacity of .3. 
x.style.opacity-=.3; //This gives an opacity of 0. Why?
x.style.opacity--; //This will give opacity of 0 as expected.

我什至试过这个:

var timesTen = x.style.opacity*10;
timesTen--;
timeTen/10;
x.style.opacity=timesTen; // This gives opacity of 0;

我希望这个问题的答案与对运营商缺乏了解有关。但是我看过大量的算术教程,它们似乎都充满了对我来说非常好用的整数示例。我什至复制粘贴了其中一些并更改了数字,却发现它们停止工作。如果这是一个菜鸟问题,我很抱歉(我确信它是)。谢谢

4

3 回答 3

2
于 2012-05-17T16:29:54.593 回答
2
x.style.opacity = parseFloat(x.style.opacity) - 0.1;

为什么这么难?

于 2012-05-17T16:26:51.020 回答
0

It doesn't work because the x.style.opacity property doesn't exist at this time, it is just applied thanks to css. Here is a workaround:

HTML:

<div id="t" style="background: black; opacity: 1;">Hello</div>
<div id="c" style="background: black;">Hello</div>

JS:

document.getElementById( 't' ).onclick = function() {
    // This works
    this.style.opacity = this.style.opacity - 0.1;
};
document.getElementById( 'c' ).onclick = function() {
    var opacity = this.style.opacity;
    // If the property exists, just decrement it
    if ( opacity ) {
        opacity -= 0.1;
    }
    // Else, set it (it will only be set once)
    else {
        opacity = 0.9;
    }
};

Demo: http://jsfiddle.net/Ralt/xDFBY/

于 2012-05-17T16:31:38.123 回答