Javascript,从`<body>` 中删除类的最快方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4397289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:14:55  来源:igfitidea点击:

Javascript, fastest way to remove a class from `<body>`

javascripthtmlcss

提问by Alex

I have a body element on which I add a few classes. And I want to remove the no-javascriptclass from it, after it's being read by the browser.

我有一个 body 元素,我在上面添加了一些类。no-javascript在浏览器读取该类之后,我想从中删除该类。

   <body class="foo boo no-javascript bla">
   <script type="javascript">
      // remove no-javascript class here
   </script>

回答by Nick Craver

Well, since extra spaces between don't matter, I'd say:

好吧,由于之间的额外空格无关紧要,我会说:

document.body.className = document.body.className.replace("no-javascript","");

You can test it out here.

你可以在这里测试一下

回答by Nick Craver

document.querySelector('body').classList.remove('no-javascript');

回答by Stephan Muller

There are no native javascript functions for this, but I always use the following code (borrowed from/inspired by this snipplr

没有针对此的原生 javascript 函数,但我总是使用以下代码(借用/受此snipplr启发)

function removeClass(ele,cls) {
   var reg = new RegExp('(\s|^)'+cls+'(\s|$)');
   ele.className = ele.className.replace(reg,' ');
}

removeClass(document.getElementById("body"), "no-javascript")

The regex does a better job than the replacefunctions mentioned in other answers, because it checks for the existence of that exact className and nothing more or less. A class named "piano-javascript" would stay intact with this version.

正则表达式比replace其他答案中提到的函数做得更好,因为它检查该确切 className 是否存在,仅此而已。名为“piano-javascript”的类将在此版本中保持不变。



For modern browsers(including IE10 and up) you could also use:

对于现代浏览器(包括 IE10 及更高版本),您还可以使用:

document.querySelector('body').classList.remove('no-javascript');

回答by sje397

document.body.className = '';

回答by darioo

You can avoid all of that work simply by using

您可以通过使用简单地避免所有这些工作

<noscript>Your browser does not support JavaScript!</noscript>

Since whatever you put inside of noscripttag will be shown if Javascript is turned off and nothing will be shown if JS is turned on.

因为noscript如果 Javascript 关闭,您在标签中放置的任何内容都将显示,而如果 JS 打开,则不会显示任何内容。