Div background change when hovering another div wi

2019-07-26 03:46发布

问题:

I am trying to get this working but I know very little of jQuery.

When an user hovers on the div "button" the background position of the div "slide" must change from "0 0" to "0 -89px", while moving the mouse to another point must reset the background position to "0 0".

That's the code (recycled from another question on stackoverflow):

    $(document).ready(function(){
    $('#button').hover(function(){
        $('#slide').css('backgroundPosition', newValue);
    }, function(){
        $('#slide').css('backgroundPosition', '0 -89px');
    });
});

My HTML:

<div id="container">
        <div id="slide"></div>
        <div id="button">Click me!</div>
</div>

My CSS:

div#slide {
  background: url(base_slide.png) no-repeat;
  width: 629px;
  height: 89px;
  background-position: 0px 0px;
}

It works, but not as expected. When I hover on the button div nothing happens, but If I move my mouse to another point all the code works and the background changes.

I am sure that there is a possibility to fix this but I just started yesterday to explore some jQuery. Also I don't know how to reset the background position to 0 0.

Could you help me please?

回答1:

I think that the var newValue should be replaced by '0 0'. If I understand your needs correctly.

Check this example: http://jsfiddle.net/VBEaQ/1/

Update: Here is a full example with fadeIn fadeOut effect ;-)

$(document).ready(function(){
    $('#button').hover(function(){
        $('#slide').stop().fadeOut(function(){
            $(this).css('backgroundPosition', '0 -89px');
        }).fadeIn();
    }, function(){
        $('#slide').stop().fadeOut(function(){
            $(this).css('backgroundPosition', '0 0');
        }).fadeIn();
    });
});​

Live demo: http://jsfiddle.net/VBEaQ/9/



回答2:

you should try to define multiple css attributes and values instead of 1 function = 1 css method that you use. The jquery documentation should help.. also its background-position not backgroundPosition.