我希望能够使用
element.style.opacity += 0.1;
或者
element.style.opacity = element.style.opacity + 0.1;
但是这种方法不起作用。透明度没有改变。如果我将不透明度设置为静态值,例如:
element.style.opacity = 0.5;
它确实可以工作。我做错了什么吗?
我希望能够使用
element.style.opacity += 0.1;
或者
element.style.opacity = element.style.opacity + 0.1;
element.style.opacity = 0.5;
它确实可以工作。我做错了什么吗?
element.style.opacity
(如果有定义)将是一个字符串,而不是一个数字。
(假设它完全被定义)"0.1" + 0.1 === "0.10.1"
您可能想要:
element.style.opacity = parseFloat(element.style.opacity) + 0.1;
我想提醒您,实际上可以通过以下方式以字符串因素减少不透明度:
element.style.opacity -= '0.1';
这样做是可行的,但反过来就不行,因为操作符+=试图将内容追加到结果字符串中。然而,可以通过执行以下操作来实现增量:
element.style.opacity -= '-0.1';
这将按照所需的方式递增它。
opacity
没有预定义的值,则为其分配一个预定义值:// using a simple onclick for demo purposes
t.onclick = function(){
var opacity = this.style.opacity;
this.style.opacity = opacity ? (parseFloat(opacity) + 0.1) : 0.2;
};
这似乎是必要的,因为如果opacity
没有在内联style
属性中定义,则该值似乎不会增加。如果您的opacity已在其中定义,则可能不需要采用此方法。
你可能想在CSS中设置关键帧并将ID或类添加到元素中。
Example for calling a keyframe:
.myElement{
position:absolute;
background:blue;
-webkit-animation:KeyframeName 1s linear infinite;
}
Example for a keyframe:
@-webkit-keyframes KeyframeName {
0%{style code here, example: opacity:1;}
100%{style code here, example: opacity:0;}
}
var OpacityValue = 1;
function OpacityChange(){
if(OpacityValue == 0.0){
Opacity = 0.0;
clearInterval(TimerName);
}
else if(OpacityValue > 0){
OpacityValue += -0.1;
}
yourElement.style.opacity = OpacityValue;
}