Pregunta

I've searched a lot to get help to answer the following question:

I would like to change a div's image-background position with jquery when hovering over a link. On mouseOut, the current position should be kept.

Use Case: http://jsfiddle.net/c9wN9/1/

I have a sprite image with four different "states". On page load, image state one (position 0 0) is shown.

By hovering over four different links (position 0 0 / 0 100 / 0 200 / 0 300) the background-position should change accordingly and keep its current position on mouseOut.

Additionally, the image change could be animated by fadeIn / fadeOut and the current active position could be made visible on the link. (active class on the <a>?)

HTML Structure:

<div id="background"></div>
<a id="link1" href="#">State 1</a>
<a id="link2"href="#">State 2</a>
<a id="link3"href="#">State 3</a>
<a id="link4"href="#">State 4</a>

CSS

#background {
height: 100px;
width: 100px;
}

jQuery

?

I made a jsfiddle with the basics and are hoping for your jQuery support: http://jsfiddle.net/c9wN9/1/

Thank you very much in advance,

frank

¿Fue útil?

Solución

I didn't include animations, but this should do exactly what you're looking for.

<style>
#background {
height: 100px;
width: 100px;
background-img:('foo.png')}
#background.hover1{background-position:0px 0px} 
#background.hover2{background-position:0px 100px}
#background.hover3{background-position:0px 200px}
#background.hover4{background-position:0px 300px}
</style>

<div id="background"></div>
<a id="hover1" class="trigger" href="#">State 1</a>
<a id="hover2" class="trigger" href="#">State 2</a>
<a id="hover3" class="trigger" href="#">State 3</a>
<a id="hover4" class="trigger" href="#">State 4</a>

<script>
$(".trigger").hover(function (){
// get hover class
var hoverClass = $(this).attr('id');
// remove active class from any trigger link
$(".trigger").removeClass('active');
// add active class to current trigger link
$(this).addClass('active');
// add hover class to the background div to shift the background position
$("#background").removeClass().addClass(hoverClass);
});
</script>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top