开发者

Change opacity of 2 items on hover

I have 2 images on my page. when I hover over img.a, it changes opacity to 0 and works perfectly. However I would like img.c to also change opacity to 0 when img.a is being hovered over. My code works for img.a but nothing for img.c

<script type='text/javascript'>
$(document).ready(function(){
$("img.a").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
},
function开发者_JS百科() {
$("img.c").stop().animate({"opacity": "0"}, "slow");
},
function() {
$("img.c").stop().animate({"opacity": "1"}, "slow");
});

});
</script>


The problem is your syntax.

jQuery's hover() function only has two arguments - the two functions. The first one is the one which is called when you mouseover the element, and the other one is called when you mouse out.

You're almost there, now all you need to do is combine the 4 functions into two functions and it will work:

<script type='text/javascript'>
$(document).ready(function(){

  $("img.a").hover(

    function() { // this function is called on mouseover img.a
        $(this).stop().animate({"opacity": "0"}, "slow");
        $("img.c").stop().animate({"opacity": "0"}, "slow");
    },
    function() { // this function is called on mouseout img.a
        $(this).stop().animate({"opacity": "1"}, "slow");
        $("img.c").stop().animate({"opacity": "1"}, "slow");
    }

  });

});
</script>


Instead of using $(this), you could use $("img.a, img.c") as your selector in the hover function.

See this fiddle for a basic example.


Give all the images that should be faded the same class. Then give all the images that should be faded together the same data-group.

<img class="fade" data-group="a" />
<img class="fade" data-group="b" />
<img class="fade" data-group="a" />

<script type="text/javascript">
$(function(){ /* shorthand for $(document).ready(function(){ */

    $('img.fade').hover(function(){

        $('img.fade[data-group="'+$(this).data('group')+'"]').stop().animate({"opacity": "0"},"slow");

    },function(){

        $('img.fade[data-group="'+$(this).data('group')+'"]').stop().animate({"opacity": "1"},"slow");

    });    

});
</script>

Now when you hover over one of the images, all the images from the same group will be faded out.

Here is my example on jsFiddle: http://jsfiddle.net/Rv9jU/


$(function () {
    $("#image1").css("opacity", 0.3);
    $("#image1").hover(function () {
        $(this).animate({ opacity: 1.0 }, 500);
    }, function () {
        $(this).animate({ opacity: 0.3 }, 500);
    });
})

Use this function within script tag in html page had section:

See Example on my blog...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜