如果你访问这个code pen然后单击主页上的任意位置,它会循环显示三个框。如果向下滚动,您也会看到内容发生变化。
我想根据当前显示的框在正确的导航栏单词下划线。
框 2 是页面加载时的默认值,然后导航栏应该在 id="home"
上激活下划线类。然后你点击它移动到方框 3,它应该将下划线类应用到 id="blog"
。
它使用左值循环遍历元素。如何仅通过查看 left 值来检查哪个框处于事件状态?
$('.box').click(function() {
$('.box').each(function() {
if ($(this).offset().left < 0)
{
$(this).css("left", "150%");
}
else if ($(this).offset().left > $('#container').width())
{
$(this).animate({
left: '0%',
}, 500 );
}
else
{
$(this).animate({
left: '-150%',
}, 500 );
}
});
});
我要申请的类(class)
.underline-active {
border-bottom: 2px solid white;
}
对应的导航栏ID:
#box1 {
left: -150%;
}
#box2 {
}
#box3 {
left: 150%;
}
另外,有没有办法让下划线从一个导航项滑动到下一个导航项?
最佳答案
您的导航栏元素可能有点太大,因为每当我向它们添加 .underline-active
类时,它都会超出元素的边缘(同时,这可能会使创建一个 css 动画更容易,因为它们看起来是这样等距的)。
在任何情况下,您都可以通过另一个 $().each()
调用来完成此操作。只需查找具有 offset.left == 0
的元素。 JQuery 提供了大量方法来向元素添加/删除 CSS 类,因此从那里它可以简单地确定哪个导航栏元素获得了我使用 switch 语句所做的 .underline-active
类。您的新 js 应如下所示:
$(document).ready(function() {
$('#home').addClass('underline-active');
$('.box').click(function() {
$('.box').each(function() {
if ($(this).offset().left < 0)
{
$(this).css("left", "150%");
}
else if ($(this).offset().left > $('#container').width())
{
$(this).animate({
left: '0%',
}, 500 );
}
else
{
$(this).animate({
left: '-150%',
}, 500 );
}
});
$('.nav-button').each(function() {
$(this).removeClass('underline-active');
});
$(".box").each(function() {
if ($(this).offset().left == 0) {
switch($(this).attr('id')) {
case 'box1':
$('#home').addClass('underline-active');
break;
case 'box2':
$('#blog').addClass('underline-active');
break;
case 'box3':
$('#about').addClass('underline-active');
break;
}
}
})
});
});
如果你想为下划线的移动设置动画,那么你应该稍微改变这个过程以使用过渡而不是从元素中删除/添加它。我想您可以使用滚动页面的相同动画来移动下划线,因为导航栏元素之间的距离似乎一致。
关于javascript - 如何根据另一个元素的左值将一个类添加到一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43621753/