3

I would expect to be able to use

element.style.opacity += 0.1;

or

element.style.opacity = element.style.opacity + 0.1;

but this does not work. The opacity does not change. If I set the opacity to a static value, like

element.style.opacity = 0.5;

it does work. What am I doing wrong?

4

5 に答える 5

8

element.style.opacity(定義されていると仮定して)数値ではなく文字列になります。

"0.1" + 0.1 === "0.10.1"

あなたはおそらく欲しい:

element.style.opacity = parseFloat(element.style.opacity) + 0.1;
于 2012-09-28T22:11:21.637 に答える
3

It occurred to me that you can actually decrease the opacity by a string factor, as following:

element.style.opacity -= '0.1';

And that will work just fine, but not the opposite since the operator += tries to append to the resulting string. Increment can however be achieved by doing

element.style.opacity -= '-0.1';

Which will increment it as wanted.

于 2014-07-20T22:39:59.673 に答える
2

I'd suggest the following, which assigns a predefined value for opacity if it's not already defined:

// 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;
};​​​

JS Fiddle demo.

This seems to be necessary because the value doesn't seem to be incremented if the opacity isn't already defined in the in-line style attribute. If that's where yours is defined then this approach may not be necessary.

于 2012-09-28T22:16:40.597 に答える
0

You might want to make keyframes setup in css and add the id or class to the element

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;}
}

The only down sides are: - you have to make a keyframe setup for all browsers. - on mobile devices it takes alot of power, meaning you page becomes un-touchable or onclickable. And makes it hard to use many keyframes at once.

Or

Try making a function in javascript and put this code in it:

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;
}

Launch this function with a timer an you got you opacity that will stop when its at a value of 0.0 Don't forget to place a var TimerName ; as global, otherwise you cant stop the timer!

于 2015-08-26T13:51:49.187 に答える
0

You can use also .toString(); method

于 2017-05-24T14:48:52.950 に答える