【问题标题】:Using jQuery, load divs with opacity of .5使用 jQuery,加载不透明度为 0.5 的 div
【发布时间】: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>

【问题讨论】:

    标签: jquery jquery-animate opacity


    【解决方案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 中设置更好的方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-04
      • 2012-06-02
      • 2023-04-03
      • 2012-08-15
      • 2012-08-06
      • 2010-10-29
      相关资源
      最近更新 更多