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に、異なる位置に 2 つの背景画像があります。最初の画像位置に変更を適用せずに、マウスクリックで2番目の画像位置を変更したい。どの構文を使用する必要がありますか?

私の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

最初の位置の元の値を読み取り、2 番目の値を変更して再割り当てする必要があります。

$("#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

これにより、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, ');
    });
});

このソリューションは、要素に背景が 2 つしかなく、各背景画像の位置やその他のプロパティを変更したい場合に適しています。

于 2012-09-02T14:48:23.413 に答える