2013-04-29 155 views
1

我有一個切換div是衆多其中之一,我需要在div打開時將div切換爲一種顏色的鏈接,並且當頁面上的另一個鏈接返回到默認顏色時被點擊。 這裏是我用來切換div的代碼,它的工作原理非常完美!當我添加普通的css代碼時,鏈接在單擊另一個鏈接時保持着色爲訪問鏈接。JQuery show hide div鏈接

function showonlyone(thechosenone) { 
    $('.newboxes').each(function (index) { 
     if ($(this).attr("id") == thechosenone) { 
      $(this).show(200); 
     } else { 
      $(this).hide(600); 
     } 
    }); 
} 

我如何可以添加到這個代碼塊中選擇時,顏色設置爲diferent顏色改回當選擇另一個鏈接的默認顏色...謝謝!

+0

你能提供一些HTML代碼示例,以顯示您的確切標記?你可以創建一個[jsfiddle](http://www.jsfiddle.net) – SirDerpington 2013-04-29 20:27:22

回答

2

最簡單的(在我看來)方法是使用.addClass().removeClass()來申請或刪除一個班級。然後,您可以使用CSS來設置顏色和任何其他設置的格式。

function showonlyone(thechosenone) { 
    $('.newboxes').each(function (index) { 
     if ($(this).attr("id") == thechosenone) { 
      $(this).addClass("highlight"); 
     } else { 
      $(this).removeClass("highlight"); 
     } 
    }); 
} 

而在你的CSS後:

.highlight a { /* may need to format differently depending on your HTML structure */ 
    color: #ff0000; /* red */ 
} 

您還可以簡化您的代碼如下所示:

function showonlyone(thechosenone) { 
    $('.newboxes.highlight').removeClass("highlight"); // Remove highlight class from all `.newboxes`. 
    $('#' + thechosenone).addClass("highlight"); // Add class to just the chosen one 
} 

此代碼將等待DOM加載,然後應用「高亮「級首次亮相<div class="newboxes">

$(document).ready(function(){ 
    $(".newboxes:first").addClass("highlight"); 
    // The :first selector finds just the first object 
    // This would also work: $(".newboxes").eq(0).addClass("highlight"); 
    // And so would this: $(".newboxes:eq(0)").addClass("highlight"); 
    // eq(n) selects the n'th matching occurrence, beginning from zero 
}) 
+0

這正是我即將發佈的內容,你擊敗了我! +1 – SamHuckaby 2013-04-29 20:34:45

+0

非常棒!謝謝!一個小東西我怎麼能設置一個潛水運行這是默認的div? – 2013-04-30 13:33:17

+0

@WebsterAlexanderIII你的意思是默認?什麼功能將與默認的div相關聯?你可以簡單地在HTML中加入'class =「highlight」',或者'class =「default」',然後按照這種方式操作,例如'$(「。newboxes.default」)。addClass(「highlight」)。 show()' – 2013-04-30 16:18:56

1
function showonlyone(thechosenone) { 
    $('.newboxes').hide(600).css('color', 'blue').find('#' + thechosenone).show(200).css('color', 'red'); 
} 

假設:此類「newboxes」包含由函數中指定的「thechosenone」指定的元素。

基於CSS的類版本:

function showonlyone(thechosenone) { 
    $('.newboxes').hide(600).removeClass('linkHilightColor').find('#' + thechosenone).show(200).addClass('linkHilightColor'); 
}