我正在尝试创建一个javascript函数,根据页面上url末尾的#tag将列添加到列表元素中。该页面有几种不同的状态,每个状态在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
抱歉缺乏清晰度。问题是如何修改首先列出的函数来添加和删除类:突出显示来自基于url中的哈希的元素,而不是像当前那样onclick。 我意识到我正在使用当前函数修改元素的样式,我会修改类而不是样式。
感谢。
答案 0 :(得分: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元素的click事件。然后在click函数中调用highlightCircularMenuIcon。 最后,在document.ready函数的最后一部分,使用URI中的哈希字符串调用highlightCircularMenuIcon。
$(document).ready(function () {
$('#circularMenu li').click(function() {
highlightCircularMenuIcon(($(this).name).replace("_link", ""));
});
highlightCircularMenuIcon(location.hash.substring(1));
});