我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。
使用锚链接,我可以使页面滚动到锚,并引导用户到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?
我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。
使用锚链接,我可以使页面滚动到锚,并引导用户到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?
当前回答
不要忘记offset()函数将元素的位置传递给文档。所以当你需要滚动你的元素相对于它的父元素时你应该使用这个;
$('.a-parent-div').find('a').click(function(event){
event.preventDefault();
$('.scroll-div').animate({
scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
}, 500);
});
关键点是获得scroll-div的scrollTop,并将其添加到scrollTop。如果你不这样做,position()函数总是会给你不同的位置值。
其他回答
对于正在寻找ReactJS (TypeScript)方法的用户。
function Hero() {
const scrollToView = (e: any) => {
e.preventDefault();
// Scroll to a certain element
document.getElementById("about-section")?.scrollIntoView({
behavior: "smooth",
});
};
return (
<section id="hero">
<button
onClick={scrollToView}
>
Learn More
</button>
</section>
);
}
export default Hero;
以及about-section组件
const AboutSection = () => {
return (
<section id="about-section" >
<h1>About Section</h1>
</section>
);
};
export default AboutSection;
$("a").on("click", function(event){
//check the value of this.hash
if(this.hash !== ""){
event.preventDefault();
$("html, body").animate({scrollTop:$(this.hash).offset().top}, 500);
//add hash to the current scroll position
window.location.hash = this.hash;
}
});
HTML
<a href="#target" class="smooth-scroll">
Link
</a>
<div id="target"></div>
或使用绝对完整的URL
<a href="https://somewebsite.com/#target" class="smooth-scroll">
Link
</a>
<div id="target"></div>
jQuery
$j(function() {
$j('a.smooth-scroll').click(function() {
if (
window.location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&& window.location.hostname == this.hostname
) {
var target = $j(this.hash);
target = target.length ? target : $j('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$j('html,body').animate({
scrollTop: target.offset().top - 70
}, 1000);
return false;
}
}
});
});
不需要任何js只是使用滚动行为:平滑的html标签就是这样
html{
scroll-behavior: smooth;
}
经过测试和验证的代码
<script>
jQuery(document).ready(function(){
// Add smooth scrolling to all links
jQuery("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
jQuery('html, body').animate({
scrollTop: jQuery(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>