jQuery 如何将类添加到 body 标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1283511/
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
How to add a class to body tag?
提问by shin
I want to add a class to a body tag with jQuery.
我想用 jQuery 向 body 标签添加一个类。
For example if the URL is http://www.mywebsite.com/about_us.asp, I want add the first five letters, in this case 'about', to the body tag:
例如,如果 URL 是http://www.mywebsite.com/about_us.asp,我想将前五个字母(在本例中为“about”)添加到 body 标记中:
<body class="about">
How can I do that?
我怎样才能做到这一点?
回答by Rex M
This should do it:
这应该这样做:
var newClass = window.location.href;
newClass = newClass.substring(newClass.lastIndexOf('/')+1, 5);
$('body').addClass(newClass);
The whole "five characters" thing is a little worrisome; that kind of arbitrary cutoff is usually a red flag. I'd recommend catching everything until an _ or .:
整个“五个字”的事情有点令人担忧;这种任意截止通常是一个危险信号。我建议在 _ 或 . 之前捕获所有内容:
newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/);
That pattern should yield the following:
该模式应产生以下结果:
../about_us.html
: about../something.html
: something- .
./has_two_underscores.html
: has
../about_us.html
: 关于../something.html
: 某物- .
./has_two_underscores.html
: 已
回答by camomileCase
Use:
用:
$(document.body).addClass('about');
回答by CMS
You can extract that part of the URL using a simple regular expression:
您可以使用简单的正则表达式提取 URL 的那部分:
var url = location.href;
var className = url.match(/\w+\/(\w+)_/)[1];
$('body').addClass(className);
回答by Hymankobec
$('body').toggleClass("className");
perfectly works
完美的作品
回答by Noon Silk
Well, you're going to want document.location
. Do some sort of string manipulation on it (unless jQuery has a way to avoid that work for you) and then
好吧,你会想要的document.location
。对其进行某种字符串操作(除非 jQuery 有办法避免为您工作),然后
$(body).addClass(foo);
I know this isn't the complete answer, but I assume you can work the rest out :)
我知道这不是完整的答案,但我认为您可以解决其余的问题:)
回答by Andrew Siemer
Something like this might work:
像这样的事情可能会奏效:
$("body").attr("class", "about");
It uses jQuery's attr()
to add the class 'about'to the body.
它使用 jQueryattr()
将类“关于”添加到正文中。
回答by Paul Ledger
I had the same problem,
我有同样的问题,
<body id="body">
Add an ID tag to the body:
向正文添加 ID 标签:
$('#body').attr('class',json.class); // My class comes from Ajax/JSON, but change it to whatever you require.
Then switch the class for the body's using the id. This has been tested in Chrome, Internet Explorer, and Safari.
然后使用 id 切换 body 的类。这已经在Chrome、 Internet Explorer 和Safari 中进行了测试。