简体   繁体   English

切换CSS Javascript函数

[英]Toggle CSS Javascript Function

I'm trying to show this CSS on the first click and remove it on the next but toggleClass doesnt seem to work and neither does my code below. 我试图在第一次点击时显示这个CSS并在下一次删除它但是toggleClass似乎没有工作,我的代码也没有在下面。 All I can get is the CSS to show and it never gets removed. 我所能得到的只是要显示的CSS,而且它从未被删除。 This is for use on Safari on iOS. 这适用于iOS上的Safari。 Thanks for the help! 谢谢您的帮助!

                var menu_enabled = false;

                $('#nav a').click(function () {
                    if (menu_enabled == true) {
                        $(this).removeClass('sf-js-enabled');
                        var menu_enabled = false;
                    }
                    else {
                        var menu_enabled = true;
                        $(this).addClass('sf-js-enabled');
                    }
                });

You should checkout .toggleClass() , looks like it's exactly what you're wanting. 你应该检查.toggleClass() ,看起来它正是你想要的。

$('#nav a').click(function () {
    $(this).toggleClass('sf-js-enabled');
});

Perhaps using the .className attribute? 也许使用.className属性?

var menu_enabled = false;

$('#nav a').click(function () {
 if (menu_enabled == true) {
  $(this).className = "";
  menu_enabled = false;
 }else 
 {
  menu_enabled = true;
  $(this).className = 'sf-js-enabled';
 }
});

I'm not exactly sure what you're trying to accomplish overall, but addClass and removeClass should work just fine. 我不确定您要整体完成什么工作,但是addClass和removeClass应该可以正常工作。 I would add an ID or class to the element that you want to have the click attached to but that's just a personal preference. 我会将ID或类添加到您想要附加点击的元素上,但这只是个人喜好。

$(document).ready(function(){
    $('#element').click(function(){
        if($('#element').hasClass('sf-js-enabled')){
            $('#element').removeClass();
        }
        else{
            $('#element').addClass('sf-is-enabled');
        }
    });
});

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

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