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

mer*_*esi 13 javascript opacity

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

在Firefox中,我使用line:

imageobject.style.MozOpacity=opacity/100;
Run Code Online (Sandbox Code Playgroud)

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

Den*_*nis 35

img.style.opacity = .5; //For real browsers;
img.style.filter = "alpha(opacity=50)"; //For IE;
Run Code Online (Sandbox Code Playgroud)

您不需要嗅探用户代理,只需设置两个值,因为浏览器将忽略不相关的值.

  • 丹尼斯:(1) .. IE:(0) (5认同)

Eri*_*ski 6

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

有很多方法可以做到这一点.

例1,设置元素样式属性,给出不透明度50%,如下所示:

<html>
  <div style='opacity:.5'>this text has 50% opacity.
  </div>
</html>
Run Code Online (Sandbox Code Playgroud)

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

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

例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>
Run Code Online (Sandbox Code Playgroud)

例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>
Run Code Online (Sandbox Code Playgroud)

例5,

导入jQuery.给你的div上课.按类选择元素并设置其.css属性,将第一个参数作为不透明度传递,将第二个参数作为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>
Run Code Online (Sandbox Code Playgroud)

示例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>
Run Code Online (Sandbox Code Playgroud)

例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>
Run Code Online (Sandbox Code Playgroud)

例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>
Run Code Online (Sandbox Code Playgroud)