开发者

Using jQuery, load divs with opacity of .5

开发者 https://www.devze.com 2023-04-02 23:38 出处:网络
I have several images on a page that have captions that overlay the bottom 50px of the image. When they load, they begin at opacity of 1, but I want them start as .5. The reason is that there\'s a hov

I have several images on a page that have captions that overlay the bottom 50px of the image. When they load, they begin at opacity of 1, but I want them start as .5. The reason is that there's a hover event that animates the opacity to 1 on hover, so I want them to start on .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>


you can set the opacity in the css or modify your script a little:

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


Just use

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

Before you assign the hover. Or like @meo pointed out you can chain it, achieves the same thing, just one less call to the dom.

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

Live Demo


Use trasparency for images in your 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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号