活动导航项
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了活动导航项相关的知识,希望对你有一定的参考价值。
当用户滚动到某个div时,我有一些代码可以将类active
添加到导航中。我也使用vue.js并且有一些不使用导航的组件。在这些组件中(我不使用导航)我收到错误:Uncaught TypeError: Cannot read property 'top' of undefined
代码:
$(document).ready(function () {
$(window).scroll(function () {
var y = $(this).scrollTop();
$('.link').each(function (event) {
// this code allows me to disable script when there's no navigation
if(!event.length) {
return;
}
if (y >= $($(this).attr('href')).offset().top) {
$('.link').not(this).removeClass('active');
$(this).addClass('active');
}
});
});
});
这段代码允许我在没有导航的情况下禁用脚本,但它也会破坏其余的代码,所以在主页面上有导航,没有添加类。
if(!event.length) {
return;
}
检查元素是否未定义
if($($(this).attr('href')).offset() != undefined && y >= $($(this).attr('href')).offset().top)
我编辑了这个答案:
.each(function(index, element){})
你可以在这里看到event
这里只是变量的名称,如果它登录到控制台你会发现它代表索引$('.link').each(function (event){})
所以event.length
是无意义的ref:。 https://api.jquery.com/each/
.link
选择器倾向于收集锚链接$($(this).attr('href'))
<a href="#selectorId">menu item</a>
所以,如果你的元素没有href
与偏移如果会抛出undefined
看来你希望`event'成为这段代码中的集合:
if(!event.length) {
return;
}
这段代码:
$('.link').each(...)
传递来自$('.link'), and it appears that single item should be and htmlAnchorElement. The HTMLAnchorElement does not have a
lengthproperty. The length property comes through the inheritance heirarchy for the
`标签创建的jQuery集合中的单个项目。
https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
看来你的意图可能是在伪代码中做这样的事情:
- 抓取所有链接(将它们放入集合中)
- 如果没有链接(集合的长度为零)不要做任何事情
- 否则(有链接)对于每个链接,找到要突出显示的那个将
active
类添加到该元素
这不是你的代码所做的。
请让我知道,如果你有任何问题。
以上是关于活动导航项的主要内容,如果未能解决你的问题,请参考以下文章