在不同浏览器中设置HTML元素的透明度

16

我需要在所有浏览器中使用JavaScript设置HTML <img src=""/> 对象的不透明度。

在Firefox中,我可以通过以下代码实现:

imageobject.style.MozOpacity=opacity/100;

在不同的浏览器中,设置元素透明度的正确JavaScript代码是什么?


拥抱jQuery。它内部处理所有跨浏览器问题。 - Diodeus - James MacFarlane
4个回答

40
img.style.opacity = .5; //For real browsers;
img.style.filter = "alpha(opacity=50)"; //For IE;

你不需要嗅探用户代理,只需设置两个值,因为浏览器会忽略无关的值。


5
好的,我会尽力进行翻译。Dennis:(1) .. IE:(0)Dennis:(1) .. IE:(0) 可能是一段对话中的文字,没有足够的上下文无法确定其意义。 - evals

8

在Javascript中设置元素的不透明度:

有许多方法可以实现此操作。

示例1,可以通过设置元素的style属性来将不透明度设置为50%,如下所示:

<html>
  <div style='opacity:.5'>this text has 50% opacity.
  </div>
</html>

例子2,如果你使用document.getElementbyId获取元素,则可以将0到1之间的数字赋值给其style.opacity属性。文本的透明度设置为20%。

<html>
 <div id="moo">the text</div>
 <script type="text/javascript">
  document.getElementById("moo").style.opacity=0.2;  
 </script>
</html>

示例3,在HTML中嵌入CSS选择器来引用您的div的类。div内的文本是黑色的,但因为其透明度为50%而呈现灰色。

<html>
  <style>
    .foobar{
      opacity: .5; 
    }
  </style>
  <div class="foobar">This text is black but appears grey on screen</div>
</html>

例子4,引入jQuery。创建一个空的div元素。使用jQuery获取该div并将其html内容设置为一个span元素,该元素设置自己的不透明度。

<html>
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js">
 </script>
 <div></div>
 <script type="text/javascript">
  $("div").html("<span style='opacity:.7'>text is 70% opacity</span>");
 </script>
</html>

示例 5

导入 jQuery。给你的 div 添加一个类。通过类选择该元素,并将其 .css 属性设置为透明度,第一个参数传递 opacity,第二个参数是介于 0 和 1 之间的数字。

<html>
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js">
 </script>
 <div class="foobar">the text</div>
 <script type="text/javascript">
  $(".foobar").css( "opacity", .5);
 </script>
</html>

示例 6,将您的元素样式设置为具有 rgba 颜色

<div style="color: rgba(0, 0, 0, .5)">
  This text color is black, but opacity of 0.5 makes it look grey.
</div>

例子 7,使用 jQuery 让浏览器花费 4 秒钟将元素淡出到 10% 的不透明度。

<html>
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js">
 </script>
 <div class="foobar">the text</div>
 <script type="text/javascript">
  $(".foobar" ).fadeTo( 4000 , 0.1, function() {
    alert("fade to 10% opacity complete");
  });
 </script>
</html>

示例8,使用animate方法告诉jQuery在5秒钟内将不透明度更改为5%。

<html>
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js">
 </script>
 <div id="flapjack">the text</div>
 <script type="text/javascript">
  $('#flapjack').animate({ opacity: 0.05 }, 5000);
 </script>
</html>

1

您不需要使用特定于供应商的前缀或浏览器检测...

只需设置opacity。Firefox、Chrome和Safari已经支持简单的opacity一段时间了,IE9及以上版本也支持opacityfilter在IE中可用。


1
在Chrome中,您只需要设置 imgobject.style.opacity=0.5; 在IE中,imgobject.style.filter='alpha(opacity=50)'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接