当我使用 smoothscroll 插件定位 name 属性时,平滑滚动不起作用,但如果我定位 id 属性,smoothscroll 工作正常。出现以下控制台错误,请建议如何解决。
$(document).ready(function() {
var class1 = $("[class^='test']");
$('class1').on('click', function (event) {
var scrollStatus = $(this).attr('data-smooth-scroll');
if(scrollStatus !== 'false' && scrollStatus !== undefined) {
var actualHrefValue = $(this).attr("href");
var actualNameValue = $('[name="' + actualHrefValue.substr(1) + '"]');
if(actualHrefValue.charAt(0) === "#") {
if(actualHrefValue !== '#' && actualHrefValue !== null) {
event.preventDefault();
document.querySelector(actualNameValue).scrollIntoView({behavior: 'smooth', block: "start" });
}
}
}
});
});
HTML:
<a type="hyperlink" class="test_1" href="#link">Click</a>
<a name="link"></a>
最佳答案
您正在使用
document.querySelector(actualNameValue)
其中actualNameValue已经是一个元素
var actualNameValue = $('[name="' + actualHrefValue.substr(1) + '"]');
尝试
actualNameValue.scrollIntoView({behavior: 'smooth', block: "start" });
而不是
document.querySelector(actualNameValue).scrollIntoView({behavior: 'smooth', block: "start" });
关于javascript - 在 JavaScript 中定位名称属性时,smoothscroll 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52000176/