[英]smooth scroll to name and ID
I have this code to scroll smoothly to a div id, but not to a name: 我有这段代码可以平滑滚动到div ID,但不能滚动到名称:
$('.scroll').on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top - 70
}, 800, function(){
window.location.hash = "#";
return false;
});
});
and this one does the opposite: 而与此相反:
$('.scroll').on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top - 70
}, 800, function(){
window.location.hash = "#";
return false;
});
});
How can I mix both codes to scroll to ID's and names in one code? 如何在一个代码中混合使用两种代码来滚动到ID和名称?
Join the selectors. 加入选择器。 This way jQuery will use the first that it finds: 这样,jQuery将使用它找到的第一个:
scrollTop: $($.attr(this, 'href') + ',[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top - 70
Just in case someone need it: 万一有人需要它:
$(function() {
$('.scroll').on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href') + ',[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top - 70
}, 800, function(){
window.location.hash = ="#";
return false;
});
});
});
Is there a way to do this with vanilla javascript? 有没有办法用香草javascript做到这一点?
The best solution I have found for doing this in vanilla javascript is to import the package https://github.com/cferdinandi/smooth-scroll 我发现在香草javascript中执行此操作的最佳解决方案是导入包https://github.com/cferdinandi/smooth-scroll
I'm not sure if I understand your question 100% but I think you could just search for the element by name using querySelector and then apply the scroll to your element that way. 我不确定我是否100%理解了您的问题,但我认为您可以使用querySelector按名称搜索元素,然后以这种方式将滚动应用于您的元素。
I was looking for an easy scroll solution earlier and came across scrollIntoView . 我之前在寻找一种简单的滚动解决方案,遇到了scrollIntoView 。 Worked like a charm and required a lot less code than any of the other solutions I found. 与我发现的任何其他解决方案一样,它的魅力十足,并且所需的代码少得多。
var foo = document.querySelector('[name="foo"]'); var bar = document.querySelector('#bar'); foo.addEventListener('click', function(){ bar.scrollIntoView({behavior: 'smooth', block: 'start'}); });
.top { width: 100%; height: 150vh; background-color: blue; text-align: center } button { margin-top: 2rem; padding: 5px 15px; font-size 18px; } .second { display: flex; justify-content: center; width: 100%; height: 100vh; background-color: green; } h1 { color: white; }
<div class="top"> <button name="foo">Click Here</button> </div> <div class="second" id="bar"> <h1>It's Working!</h1> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.