如何在 Javascript 中动态更改图像不透明度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9062126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dynamically change image opacity in Javascript
提问by Andrey Rubliov
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):
我使用以下代码在 Javascript 中设置图像透明度,但它仅适用于 Internet Explorer(在 FireFox、Opera、Safari 和 Google Chrome 中它仍然不透明):
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?
你能帮忙吗?
回答by Andy E
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:
您可以只使用一个数字作为opacity
属性:
img.style.filter = "alpha(opacity=75);";
img.style.MozOpacity = 0.75;
img.style.opacity = 0.75;
img.style.KhtmlOpacity = 0.75;
回答by jfriend00
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/
你可以在这里看到它的工作:http: //jsfiddle.net/jfriend00/tnDaD/
MozOpacity and KhtmlOpacity should no longer be needed. The browsers that required those are long, long gone from use.
不再需要 MozOpacity 和 KhtmlOpacity。需要这些的浏览器已经很久很久没有使用了。
回答by Aram Kocharyan
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);