我正在尝试实现一种交互,其中当 a 处于 View 中时,将类添加到特定菜单项。不幸的是,我收到以下错误:
Uncaught Error: Syntax error, unrecognised expression: [href=#contact]
提前谢谢您。
伪代码
- 滚动页面
- 当该部分处于 View 中时,向相应的导航项添加一个类
JavaScript
// Cache selectors
var lastId,
topMenu = $('#top-menu'),
topMenuHeight = topMenu.outerHeight() + 1,
// All list items
menuItems = topMenu.find('a'),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function() {
var item = $($(this).attr('href'))
if (item.length) {
return item
}
})
// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e) {
var href = $(this).attr('href'),
offsetTop = href === '#' ? 0 : $(href).offset().top - topMenuHeight + 1
$('html, body').stop().animate(
{
scrollTop: offsetTop,
},
850,
)
e.preventDefault()
})
// Bind to scroll
$(window).scroll(function() {
// Get container scroll position
var fromTop = $(this).scrollTop() + topMenuHeight
// Get id of current scroll item
var cur = scrollItems.map(function() {
if ($(this).offset().top < fromTop) return this
})
// Get the id of the current element
cur = cur[cur.length - 1]
var id = cur && cur.length ? cur[0].id : ''
console.log('Cur', cur, 'ID', id)
if (lastId !== id) {
lastId = id
// Set/remove active class
menuItems.parent().removeClass('active').end().filter('[href=#' + id + ']').parent().addClass('active')
}
})
最佳答案
对于属性选择器中的引号,jQuery 非常挑剔。您必须使用带引号的字符串作为值(单精度或 double )。
更改:
filter('[href=#' + id + ']')
致:
filter('[href="#' + id + '"]')
如果您想要稍微不那么精确,但又可以删除 #
,您也可以使用 ~=
而不仅仅是 =
.
关于javascript - JavaScript — 未捕获错误 : Syntax error, 无法识别的表达式:[href=#contact] (WordPress),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53438387/