使用 jQuery,加载不透明度为 0.5 的 div

Posted

技术标签:

【中文标题】使用 jQuery,加载不透明度为 0.5 的 div【英文标题】:Using jQuery, load divs with opacity of .5 【发布时间】:2011-11-12 04:14:10 【问题描述】:

我在一个页面上有几张图片,它们的标题覆盖了图片底部 50 像素。当它们加载时,它们以不透明度 1 开始,但我希望它们以 0.5 开始。原因是有一个 hover 事件在悬停时将不透明度设置为 1,所以我希望它们从 0.5 开始。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() 
    $('.fade').hover(function()  
        $(this).stop().animate("opacity": 1); 
    ,function()  
        $(this).stop().animate("opacity": .5); 
    );
);
</script>
</head>
<body>
<div class="image_w_caption" style="float:left;margin:5px;">

    <div class="image" style="width:250px;height:188px;background:url(images/image.jpg) no-repeat 0 0;">
    </div>

    <div class="fade" style="width:250px;height:188px;background:url(images/image_2.png) no-repeat 0 0;position:relative;top:-203;z-index:2;">
        <p style="padding:150px 5px 0 5px;z-index:3;color:white;">text</p>
    </div>

</div>

<div class="image_w_caption" style="float:left;margin:5px;">

    <div class="image" style="width:250px;height:188px;background:url(images/image_2.jpg) no-repeat 0 0;">
    </div>

    <div class="fade" style="width:250px;height:188px;background:url(images/image_2.png) no-repeat 0 0;position:relative;top:-203;z-index:2;">
        <p style="padding:150px 5px 0 5px;z-index:3;color:white;">more text</p>
    </div>

</div>

</body>
</html>

【问题讨论】:

【参考方案1】:

您可以在 css 中设置不透明度或稍微修改您的脚本:

$(document).ready(function()
    $('.fade').hover(function()  
        $(this).stop().animate("opacity": 1); 
    ,function()  
        $(this).stop().animate("opacity": .5); 
    ).css("opacity", 0.5);
);

【讨论】:

【参考方案2】:

随便用

$('.fade').css(opacity : '.5')

在分配悬停之前。或者像@meo 指出的那样,您可以链接它,实现相同的目标,只需少调用一次 dom。

$('.fade').hover(....).css(opacity : '.5')

Live Demo

【讨论】:

做到了。谢谢。是的,我应该知道的。我会接受的。 或者他可以在悬停后将其链接起来以避免选择相同的元素两次。 @Adam 你应该考虑在我的例子中提到的悬停之后链接你的css命令。【参考方案3】:

对 CSS 中的图像使用透明度:

.fade
  /* IE 8 */
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";

  /* IE 5-7 */
  filter: alpha(opacity=50);

  /* Netscape */
  -moz-opacity: 0.5;

  /* Safari 1.x */
  -khtml-opacity: 0.5;

  /* Good browsers */
  opacity: 0.5;

【讨论】:

+1 我必须同意这是比在 JS 中设置更好的方法。

以上是关于使用 jQuery,加载不透明度为 0.5 的 div的主要内容,如果未能解决你的问题,请参考以下文章

jQuery应用css不透明度

具有不透明度的 jQuery 动画

不透明度为 0.5 的 CSS 背景图像

Jquery在滚动上动画div不透明度

jQuery常用操作部分总结

避免嵌套网格之间的不透明度继承