如何使用JavaScript或jQuery在单击时切换任何CSS属性?

3

我对JavaScript非常陌生,但是我需要实现一个功能,例如我有一个白色背景的按钮,当我点击后它的背景应该变成黑色,再次点击时它的背景应该再次变成白色。意思是我需要在点击同一个按钮时改变其背景颜色,请帮帮我,我真的很困惑,而且我也正在学习JavaScript,如果你可以告诉我更多关于JavaScript或除了我需要的东西之外的任何想法,我会很感激你的,谢谢。


我知道你是JavaScript的新手,但你尝试过什么呢? - vol7ron
2个回答

4
你可以尝试这样做:

HTML:

<button class="btn">Toggle Background</button>

CSS:

.btn{
    background:#fff;
}

.btn_red{
    background:red;
}

JS:

$(function(){
    $('.btn').on('click', function(){
        $(this).toggleClass('btn_red')
   });
});

示例.

纯JavaScript:

window.onload = function(){
    document.querySelector('.btn').onclick = function(){
        if(this.className.match('btn_red')) {
            this.className = 'btn';
        }
        else {
            this.className = 'btn btn_red';
        }
    };
};

演示. 还有其他方法,但这只是一些想法。


同时,在Vanilla JS中,您也可以使用element.classList.toggle("btn_red")。请参阅文档 - Splines

1

一个jQuery的解决方案是

http://jsfiddle.net/zMrtL/(我将文本颜色设置为红色,以便在切换时不会出现黑色文本在黑色背景上即看不见。)

CSS

#div { /* use any selector that matches your desired element */
    background-color: #FFF;
}

#div.dark { /* the "dark" class to be added by jQuery, 
               put your above selector in front to increase specificity */
    background-color: #000;
}

关于“特异性”问题,如果您在 dark 前面不添加 #div#div 的定义将覆盖 .dark 的定义,即使它是由 jQuery 添加的,该 div 仍将保持白色。如果您想了解更多,请查看 thisthis
// ensure HTML is ready/completely loaded, so that you won't end up 
// binding click to something non-existent (at the time the binding occurs)
// Trying to bind something non-existent will not work because jQuery can never know
// if there is such element in the future, unless you use delegates (far fetched)
$(function(){ 
    // on click, bind the "click" event to your element, and do something
    $('#div').click(function(){
        $(this).toggleClass('dark'); // on click, toggle the class of the element clicked
        // i.e. if the class does not exist, add it, otherwise remove it.
        // in jQuery, "this" is the element clicked/mouse-overed/etc.. i.e. target of the event
        // in functions passed to jQuery event-binding functions.
        // CSS/browsers is smart enough to detect these class changes and apply styles to new elements.
    });
});

#div 表示一个带有 id 为 div 的元素,即 <div id="div"></div>,因为 # 表示具有以下 ID 的元素。如果你使用的是 class,即 <div class="div"></div>,请使用 .div

clicktoggleClass将函数传递给 jQuery 构造函数 的文档。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接