2010-05-20 30 views
1

我想創建一個JavaScript函數來添加和刪除一個類到列表元素的基礎上#tag在頁面上的URL結束。這個頁面有幾種不同的狀態,每個狀態在URL中都有不同的#號。Javascript函數將類添加到基於URL中的#列表元素

我目前使用這個腳本,當用戶第一次加載頁面時,基於URL中的#改變給定元素的樣式,但是如果用戶導航到頁面的不同部分,頁面加載保持,我希望它改變。

<script type="text/javascript"> 

var hash=location.hash.substring(1); 

if (hash == 'strategy'){ 
document.getElementById('strategy_link').style.backgroundPosition ="-50px"; 
} 
if (hash == 'branding'){ 
document.getElementById('branding_link').style.backgroundPosition ="-50px"; 
} 
if (hash == 'marketing'){ 
document.getElementById('marketing_link').style.backgroundPosition ="-50px"; 
} 
if (hash == 'media'){ 
document.getElementById('media_link').style.backgroundPosition ="-50px"; 
} 
if (hash == 'management'){ 
document.getElementById('mangement_link').style.backgroundPosition ="-50px"; 
} 

if (hash == ''){ 
document.getElementById('shop1').style.display ="block"; 
} 

</script> 

此外,我使用的功能改變類元素的onClick的,但是,當用戶從另一頁涉及到一個特定的#在頁面上直接再點擊到不同的位置,兩個元素出現活性。

<script type="text/javascript"> 
function selectInList(obj) 
{ 
    $("#circularMenu").children("li").removeClass("highlight"); 
    $(obj).addClass("highlight"); 
} 
</script> 

你可以在這裏看到: http://www.perksconsulting.com/dev/capabilities.php#branding

對不起,缺乏清晰度。問題是如何修改首先列出的函數以添加和刪除類:突出顯示,基於網址中的哈希而不是像當前那樣點擊。 我意識到我正在用當前函數內聯元素的樣式,我會修改類而不是樣式。

謝謝。

+1

在上述文本中沒有一個問題 - 請形成一個問題。 – 2010-05-20 19:49:52

+0

非常好的網站,但我不明白你的問題... – Rbacarin 2010-05-20 20:09:20

+0

John Hartsock有解決方案,但是,肖恩,你可能想再次看看你的代碼 - 沒有元素與id = shop1作爲去http:///www.perksconsulting.com/dev/capabilities.php#doesnotexist說明 – 2010-05-20 20:32:38

回答

1

你的問題是你的第一個JavaScript代碼塊。如果你設置了元素的樣式,它總是會覆蓋元素上的任何類樣式。目前,當您使用散列#strategy導航到頁面時,您可以修改元素的內聯樣式。我會建議修改你的代碼來修改元素的類。

var hash=location.hash.substring(1); 

$('#' + hash + '_link').addClass('highlight'); 

if (hash == ''){ 
    $('#shop1').show() 
} 

編輯(關於你的評論)

這裏是我會做什麼:

首先創建一個功能,增加了亮點類特定的哈希值和刪除突出顯示類所有其他人。傳遞無效散列值時,您可能需要默認操作。

function highlightCircularMenuIcon(hashValue) { 
    if (hashValue.length) { 
    $('#circularMenu li').removeClass('highlight'); 
    $('#' + hash + '_link').addClass('highlight'); 
    } else { 
    //default action you did have $('#shop1').show(); 
    } 
} 

其次,當文檔準備好(或加載),結合用於每個在circularMenu的LI元素的單擊事件。然後在點擊函數調用highlightCircularMenuIcon。 最後,在document.ready函數的最後一部分,使用URI中的哈希字符串調用highlightCircularMenuIcon。

$(document).ready(function() { 
    $('#circularMenu li').click(function() { 
    highlightCircularMenuIcon(($(this).name).replace("_link", "")); 
    }); 

    highlightCircularMenuIcon(location.hash.substring(1)); 
}); 
+0

感謝您的答案約翰。這幾乎是我需要的。但是,如果要導航到頁面perksconsulting.com/dev/capabilities.php#branding,然後單擊左側的其中一個圓圈以查看頁面的另一部分,則活動(「高亮」)類不會更改。 有沒有一種方法可以在頁面加載後使用您在此處介紹的方法進行更改? – Jason 2010-05-20 22:56:44

+0

只是爲了讓你知道你有點擊事件掛鉤李元素,但你評論他們。我在編輯的答案中提供了。我將如何解決這個問題。看一看。順便說一下你的網站看起來不錯。做得好。 – 2010-05-21 12:58:37

相關問題