English 中文(简体)
我想更改所有同级元素的样式
原标题:I want to change the style of all sibling elements

我正在为选项卡式导航界面使用按钮。我希望活动选项卡为红色,其余选项卡为黑色。

<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,这样这个页面就不会重新加载。

最佳回答

你想做额外的工作。。。为什么不保留对当前选定选项卡的引用,然后在进行新选择时重置其样式。

此外,使用CSS类比内联样式更好(这样,您就不需要使用Javascript来更改选项卡的外观):

<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>
问题回答

暂无回答




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签