我想更改所有兄弟元素的样式 [英] I want to change the style of all sibling elements
问题描述
我正在使用用于选项卡式导航界面的按钮。我希望活动的标签为红色,其余的为黑色。
I am using buttons for a tabbed navigation interface. I want to have the active tab red, and the rest black.
<div class="tabs">
<button type="button" onclick="selectTab(this);">Astringents</button>
<button type="button" onclick="selectTab(this);">Exfoliators</button>
<button type="button" onclick="selectTab(this);">Moisturizers</button>
</div>
function selectTab(activeTab){
var siblings = activeTab.parentNode.childNodes;
for (s in siblings){
s.style.color='black';
}
activeTab.style.color='red';
我在正确访问兄弟姐妹时遇到了问题。除了这三个按钮之外,还有更多的按钮,因此我需要动态解决。我将使用Ajax,因此不会重新加载此页面。
I am having problems accessing the siblings properly. There are more buttons than these three so I need to solve this dynamically. I will be using Ajax so this page will not reload.
推荐答案
您正在尝试做额外的工作...为什么不保留
You are trying to do extra work... Why not keep a reference to the currently selected tab, then when a new selection is made, reset its style.
此外,为此,使用CSS类比内联样式要好得多。 (这样一来,您就无需弄乱Javascript来更改标签的外观):
Also, it is much better to use CSS classes than inline styles for this (this way, you don't need to muck about with Javascript to change how your tabs look):
<style>
.tab { color: black; }
.tab-selected { color: red; }
</style>
<div class="tab" onclick="selectTab(this)">Tab 1</div>
<div class="tab" onclick="selectTab(this)">Tab 2</div>
<!-- More tabs -->
<script>
var selectedTab = null;
function selectTab(tab) {
if (selectedTab) { selectedTab.className = 'tab'; }
tab.className = 'tab-selected';
selectedTab = tab;
}
</script>
这篇关于我想更改所有兄弟元素的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!