我有一个关于部分,为了便于阅读,我将其分成多个由 JavaScript 加载的部分。我希望它的侧边导航具有不同的背景颜色,如果它被悬停在上面并且它是被选中的,并且还具有每个选项的具有独特颜色的边框。我让它工作没有问题,但我只是想知道是否有比我现在的方式更有效的方法。
简而言之,HTML:
<nav>
<p id="bout" onclick="bout()">About Us</p>
<p id="mish" onclick="mish()">Our Mission</p>
<p id="team" onclick="team()">The Team</p>
<p id="how" onclick="how()">How It Works</p>
<p id="poli" onclick="poli()">Policies</p>
</nav>
<div class="actual">
<div id="about">
<h2>About Us</h2>
<p>We are a conglomerate of hoodlums.</p>
</div>
</div><!-- end actual -->
和 JS:
function bout() {
document.getElementById("about").innerHTML= '<h2>About Us</h2><p>We are a conglomerate of hoodlums.</p>';
document.getElementById("bout").style.borderRight='3px solid red';
document.getElementById("mish").style.borderRight='none';
document.getElementById("team").style.borderRight='none';
document.getElementById("how").style.borderRight='none';
document.getElementById("poli").style.borderRight='none';
document.getElementById("bout").style.backgroundColor='ghostwhite';
document.getElementById("mish").style.backgroundColor='bisque';
document.getElementById("team").style.backgroundColor='bisque';
document.getElementById("how").style.backgroundColor='bisque';
document.getElementById("poli").style.backgroundColor='bisque';
}
function mish() {
document.getElementById("about").innerHTML = '<h2>Mission</h2><p>Our mission is to rid the world of dust bunnies.</p>';
document.getElementById("bout").style.borderRight='none';
document.getElementById("mish").style.borderRight='3px solid orange';
document.getElementById("team").style.borderRight='none';
document.getElementById("how").style.borderRight='none';
document.getElementById("poli").style.borderRight='none';
document.getElementById("bout").style.backgroundColor='bisque';
document.getElementById("mish").style.backgroundColor='ghostwhite';
document.getElementById("team").style.backgroundColor='bisque';
document.getElementById("how").style.backgroundColor='bisque';
document.getElementById("poli").style.backgroundColor='bisque';
}
如您所见,在单击时必须显式关闭每个样式非常麻烦。不过,主要的关键是让每个 border-right 的颜色不同。
这是一个关于整个事情的 jsfiddle,但出于某种原因,它实际上并没有确认 JS:http://jsfiddle.net/4CrhD/
其他随机问题:是否可以链接到此页面并加载与 about 不同的内容,例如,我可以链接到此页面并加载“mish()”而不是 HTML 中的内容吗?
最佳答案
最好的方法是使用 CSS。在父元素上添加删除类并让 CSS 应用正确的规则。
body.mish #bout{
border-right : 3px solid red,
}
body.bout #bout{
border-right : 3px solid blue,
}
关于javascript - 使用 Javascript 更改样式的更有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17727296/