我的页面上有一个菜单,其中有一个人可以导航到的4个不同区域:
Home
About
Contact
Privacy
我希望当用户点击其中一个链接时,我会在菜单中看到它的指示。因此,如果用户点击“关于”,他将会看到
Home
-->About
Contact
Privacy
我正在使用带有jquery的ol来填充页面的另一部分,其中包含与被点击主题相关的数据。
我的HTML:
<div class='home'><a href='#' class='navigate' id='home'><ol>Home</ol></a></div>
<div class='about'><a href='#' class='navigate' id='about'><ol>About</ol></a></div>
<div class='contact'><a href='#' class='navigate' id='contact'><ol>Contact</ol></a></div>
<div class='privacy'><a href='#' class='navigate' id='privacy'><ol>Privacy</ol></a></div>
导航类:
$('.navigate').click (function() {
//Show a animiated gif
$('#loading').show();
//id of module
var module = $(this).attr('id');
//get id of modules a href id
var childId = $("."+module).children("a").attr("id");
//add --> to the div
$('.'+$(this).attr('id')).html("-->"+childId);
//post to navigate.php and do stuff.
$.ajax({
type: "POST",
url: "navigate.php",
data: "module="+module,
success: function(result)
{
$('#mainBody').html(result);
$('#loading').hide();
}
})
})
});
通过这次尝试,我可以得到一个“ - &gt;”但是,在正确的OL中,我无法移除其他人并丢失href链接。很明显,我要替换 - &gt;当我想出这个时,带着一个很酷的小箭头图像。
这是我的小提琴: http://jsfiddle.net/Q4H2k/1/
答案 0 :(得分:6)
如下:
<强> JS 强>
$('.navigate').removeClass('active'); // Remove active from all elements in the menu
$(this).addClass('active'); // Add active class to the element being clicked
<强> CSS 强>
.active:before {
content: "---> "; // Apply styling for the active element here
}
Imo,通过给它一个类来指示活动的menu-element更“干净”。这样你就可以简单地删除类而不必乱用inner-html。您还可以更好地控制样式的方式。如果你想要--->
之外的其他东西,你可以设计一种特殊的颜色,子弹或其他东西。看看其他网站是如何做到的。
答案 1 :(得分:2)
作为@ OptimusCrime代码的替代方案,您只需执行以下操作:
// Match all navigate
$('.navigate').click(function () {
// Delete all the arrows
$("ol .current").remove();
// Add the arrow only in the relevant one
$(this).find("ol").prepend("<span class = 'current'>--></span>");
});
JSFIDDLE。它更复古兼容,我发现它更容易。
此外,我将html更改为
<nav>
<ul>
<li>
<a data-link = "home">
Home
</a>
</li>
<li>
<a data-link = "about">
About
</a>
</li>
</ul>
</nav>
因为它比现在的语义和SEO更友好。然后jquery更简单:
// Match all navigate
$('nav a').click(function () {
// Delete all the arrows
$("nav .current").remove();
// Add the arrow only in the relevant one
$(this).prepend("<span class = 'current'>--></span>");
});