开发者

jQuery - black & white image to color image (hover)

开发者 https://www.devze.com 2023-02-25 11:38 出处:网络
I have black and white image contained in a css: http://cl.ly/3G0E0g1e2G2h3k3U3F2O In the same file I put in color image:

I have black and white image contained in a css:

http://cl.ly/3G0E0g1e2G2h3k3U3F2O

In the same file I put in color image:

http://cl.ly/1l2A2F0o1j3E1z2s223V

Now I wants to when you hover the mouse on 开发者_如何转开发this image has changed from black and white to color...

I put the function in jQuery:

    $("ul li").mouseover(function() {

        $(this).find("span.thumb").hover().css({
            'background-position': 'center bottom'
        }).stop().fadeTo(400, 0).show();

    });

    $("ul li").mouseout(function() {

        $(this).find("span.thumb").hover().css({
            'background-position': 'center top'
        }).stop().fadeTo(400, 1).show();

    });

HTML:

<span class="thumb"></span>

CSS:

ul li span.thumb {background:url(image.png) no-repeat}

Q: How I can do it differently? (that when you hover the mouse on the image did not disappear).


Hi looks to me that you've over complicated it slightly, try this:

HTML

<div>
  <img src="http://ajthomas.co.uk/flower-col.png" alt="" />
</div>

JQUERY

$(document).ready(function() {
    $('div').mouseover(function(){
        $('img').fadeIn('slow');
    });
    $('img').mouseout(function(){
        $('img').fadeOut('slow');
    });
});

CSS

div{width:300px;
    height:300px;
    background-image:url(http://ajthomas.co.uk/flower-gs.png)}

img{display:none;}

I've coded it up for you too on JSFiddle


Try CSS sprites: http://www.alistapart.com/articles/sprites

The basic technique is to combine both images to one background image and set it as the background of your html element. Then when a hover event occurs you only "move" the background image to the position where the coloured part of the background image is visible. With the background-position css property you can control which part of the background image is visible.

The advantage is that there is no delay when hovering the first time as the bw as well as the coloured version of the image are loaded on page load.

0

精彩评论

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

关注公众号