简体   繁体   English

点击 jquery 更改 css 样式

[英]change css style on click with jquery

I have the following click event.我有以下点击事件。 I would also like to toggle the background-position: between top and bottom on click.我还想在点击时切换背景位置:在顶部和底部之间。

$('.close').click(function () {
    $('.banner-inner-content').slideToggle('slow', function () {
    });
});

So how can i toggle between?那么我该如何切换呢?

.close{background-position:top}

and

.close{background-position:bottom;}

You can pass a function to .css() :您可以将 function 传递给.css()

$(this).css('background-position', function(i, val) {
    return val === 'top' ? 'bottom' : 'top';
});

Or you define a new class:或者你定义一个新的 class:

.close.bottom {
    background-position: bottom;
}

and use .toggleClass() :并使用.toggleClass()

$(this).toggleClass('bottom');

you could use two differents css class (one for top and the other for bottom) and when onClick event is shooted change it.您可以使用两种不同的 css class(一个用于顶部,另一个用于底部),当 onClick 事件被拍摄时更改它。

    $('.close').click(function () {
        if($('.banner-inner-content').hasClass('top')){
            $('.banner-inner-content').removeClass('top');
            $('.banner-inner-content').addClass('bottom');
    }else{
            $('.banner-inner-content').addClass('top');
            $('.banner-inner-content').removeClass('bottom');
    }
});

try using isvisible to check if its being displayed or not and add the respective position:尝试使用 isvisible 检查其是否显示并添加相应的 position:

$('.close').click(function () {
    $('.banner-inner-content').slideToggle('slow', function () {
        if( $(this).is(':visible') ) {
            $(this).css({backgroundPosition: 'top'});
        }
        else {
            $(this).css({backgroundPosition: 'bottom'});
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM