简体   繁体   中英

How to dynamically change image opacity in Javascript

I am using the following code to set image transparency in Javascript, but it only works in Internet Explorer (and in FireFox, Opera, Safari and Google Chrome it remains non-transparent):

img = new Image();

img.src = "...";

img.style.filter       = "alpha(opacity=75);";
img.style.MozOpacity   = "0.75;";
img.style.opacity      = "0.75;";
img.style.KhtmlOpacity = "0.75;";

Can you please help?

The problem is the ; in the string, which is assumed to be part of the value by the browser and, therefore, results in an invalid number.

You can just use a number for the opacity property:

img.style.filter       = "alpha(opacity=75);";
img.style.MozOpacity   = 0.75;
img.style.opacity      = 0.75;
img.style.KhtmlOpacity = 0.75;

Remove the semi-colon from inside the quotes like this:

img.style.filter       = "alpha(opacity=75)";
img.style.opacity      = "0.75";

or without the quotes all together:

img.style.filter       = "alpha(opacity=75)";
img.style.opacity      = 0.75;

You can see it work here: http://jsfiddle.net/jfriend00/tnDaD/

MozOpacity and KhtmlOpacity should no longer be needed. The browsers that required those are long, long gone from use.

Don't give the ; in the value, it'll do that for you :)

img = new Image();
img.src = "http://jsfiddle.net/img/logo.png";
img.style.opacity = "0.3";
document.body.appendChild(img);

http://jsfiddle.net/Cdjc6/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM