Change background position with jQuery

2019-01-17 19:51发布

I'd like to change the background position of a CSS-class while hovering a li-element.

HTML:

<div id="carousel">
    <ul id="submenu">
        <li>Apple</li>
        <li>Orange</li>
    </ul>
</div>

CSS:

#carousel { 
    float: left;
    width: 960px;
    height: 360px;
    background: url(../images/carousel.png);
}

Any suggestions on how to do this?

5条回答
老娘就宠你
2楼-- · 2019-01-17 20:01

rebellion's answer above won't actually work, because to CSS, 'background-position' is actually shorthand for 'background-position-x' and 'background-position-y' so the correct version of his code would be:

$(document).ready(function(){
    $('#submenu li').hover(function(){
        $('#carousel').css('background-position-x', newValueX);
        $('#carousel').css('background-position-y', newValue);
    }, function(){
        $('#carousel').css('background-position-x', oldValueX);
        $('#carousel').css('background-position-y', oldValueY);
    });
});

It took about 4 hours of banging my head against it to come to that aggravating realization.

查看更多
Juvenile、少年°
3楼-- · 2019-01-17 20:09
$('#submenu li').hover(function(){
    $('#carousel').css('backgroundPosition', newValue);
});
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-17 20:10

You guys are complicating things. You can simple do this from CSS.

#carousel li { background-position:0px 0px; }
#carousel li:hover { background-position:100px 0px; }
查看更多
冷血范
5楼-- · 2019-01-17 20:18

Here you go:

$(document).ready(function(){
    $('#submenu li').hover(function(){
        $('#carousel').css('background-position', '10px 10px');
    }, function(){
        $('#carousel').css('background-position', '');
    });
});
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-17 20:23

Sets new value for backgroundPosition on the carousel div when a li in the submenu div is hovered. Removes the backgroundPosition when hovering ends and resets backgroundPosition to old value.

$('#submenu li').hover(function() {
    if ($('#carousel').data('oldbackgroundPosition')==undefined) {
        $('#carousel').data('oldbackgroundPosition', $('#carousel').css('backgroundPosition'));
    }
    $('#carousel').css('backgroundPosition', [enternewvaluehere]);
},
function() {
    var reset = '';
    if ($('#carousel').data('oldbackgroundPosition') != undefined) {
        reset = $('#carousel').data('oldbackgroundPosition');
        $('#carousel').removeData('oldbackgroundPosition');
    }
    $('#carousel').css('backgroundPosition', reset);
});
查看更多
登录 后发表回答