2

我有一个简单的 HTML :<div id="wrapper"></div>和这个样式表:

#wrapper{

        position: absolute;

        width: 400px;
        height: 400px;     

        background-image: url(img1.png), url(img2.png);

        background-repeat: no-repeat, no-repeat;

        background-position: top center, center center;

        background-color: green;
        border: 1px solid black;

}  

如上面的样式表所示#wrapper,在不同的位置有两个背景图像。我想在鼠标单击时更改第二个图像位置,而不对第一个图像位置应用任何更改。我必须使用什么语法?

我的jQuery代码:

$("#wrapper").click(function(){
    this.css("background-position": " ? , bottom right " );
});

我认为?应该替换为类似!important!important不适用于在第一张图像上应用不更改的东西。

两个背景图像的位置会在不同的地方发生变化,我现在不知道第一个图像位置是什么,我可以将其位置保存在一个变量中,但我宁愿使用本机解决方案,如果有
任何建议吗?

4

5 回答 5

1

使用多个背景,背景和涉及背景的所有其他属性都是逗号分隔的列表,所以您所要做的就是使用与“不”相同的 CSS 规则对第一个背景图像的位置进行任何更改:

$("#wrapper").on('click', function(){
    $(this).css("background-position", "top center, bottom right");
});

另一种选择是在类中设置背景位置,然后只交换类:

.bg1 {background-position: top center, center center;}
.bg2 {background-position: top center, bottom right;}

-

$("#wrapper").on('click', function(){
    $(this).toggleClass('bg1 bg2');
});
于 2012-09-02T14:41:21.053 回答
1

您需要明确指定两个图像的位置(即使是一个不变的位置,因为据我所知,没有办法跟踪哪个图像是哪个):

$('#wrapper').click(
    function(){
        $(this).css({
            'background-position': 'top center, center center'
        });
    });

另外,请注意本机 DOMthis不能使用 jQuery 方法,您必须使用 jQuery$(this)对象。

于 2012-09-02T14:41:29.567 回答
1

您需要读取第一个位置的原始值,然后将其与更改的第二个值一起重新分配。

$("#wrapper").click(function(){
   var first = $(this).css("background-position").split(',')[0];
   $(this).css("background-position", first + ", bottom right " );
});
于 2012-09-02T14:44:20.293 回答
1

改变背景位置 2

这会将第二个背景位置(逗号后)替换为bottom right

$('#wrapper').click(function() {
    $(this).css('background-position', function() {
        return this.style.backgroundPosition.replace(/,(.*)$/, ', bottom right');
    });
});

改变背景位置 1

这会将第一个背景位置(逗号之前)替换为bottom right

$('#wrapper').click(function() {
    $(this).css('background-position', function() {
        return this.style.backgroundPosition.replace(/(.*),/, 'bottom right, ');
    });
});

如果元素只有两个背景并且我们想要更改每个背景图像的位置或任何其他属性,此解决方案是一个不错的选择

于 2012-09-02T14:48:23.413 回答
0

纯 CSS:

body {

  background-image:
    url(https://...image1),
    url(https://...image2);

  background-position:
    top 10% left 10%,
    top 10% right 10%;
}
于 2020-01-20T12:53:37.097 回答