当您在特定 div 上时,使用 Javascript 向 <li> 添加/删除类。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10272107/
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
Add/Delete class to <li> with Javascript when you are on specific div.
提问by Kiyro
I open this thread to ask your help with JavaScript.
我打开这个线程来请求你对 JavaScript 的帮助。
My website is divided vertically into four main div.
我的网站垂直分为四个主要 div。
<div id="homepage"> Content </ div>
<div id="page1"> Content </ div>
<div id="page2"> Content </ div>
<div id="page3"> Content </ div>
<div id="page4"> Content </ div>
On the right of page there is navigation menu, div position: fixed.
页面右侧有导航菜单,div位置:固定。
<div id="nav">
<ul>
<li> <a href="#homepage"> Homepage </ a> </ li>
<li> <a href="#page1"> Page1 </ a> </ li>
<li> <a href="#page2"> Page2 </ a> </ li>
<li> <a href="#page3"> Page3 </ a> </ li>
<li> <a href="#page4"> page4 </ a> </ li>
</ ul>
</ div>
I wish that when you are in a div container (page1 or page2 etc) is added to a class corresponding menu item.
我希望当你在一个 div 容器(page1 或 page2 等)中添加一个类对应的菜单项时。
And 'possible to do this with javascript? Thanks in advance
和'可以用javascript做到这一点吗?提前致谢
回答by Nidis
You will use the node tree for setting attribute. What i mean
您将使用节点树来设置属性。我的意思是
var node = document.getElementById("dividname").getElementsByTagName("li")[i];
node.setAttribute("class", "classname");
for deleting the class just use above without any value
删除类只是使用上面没有任何值
node.setAttribute("class", "");
回答by mkk
a simplest solution in jquery that comes to my mind would be something like:
我想到的 jquery 中最简单的解决方案是这样的:
$('.menu-link').click(function(){
var divId = $(this).attr("href");
$('.page-div').removeClass("special-class");
$(divId).addClass("special-class");
});
please note that .menu-link
is a class for your <a>
inside <li>
and .page-div
is a class for divs with ids page1
, page2
etc.
请注意,.menu-link
是你的一个类<a>
里<li>
,并.page-div
是与IDS的div类page1
,page2
等等。