2010-05-20 35 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

相关问题