gpt4 book ai didi

javascript - 如何一次不快速地轻柔滚动

转载 作者:行者123 更新时间:2023-11-28 03:37:30 31 4
gpt4 key购买 nike

我是 html 的初学者,想问一下如何移动到 html 中的 id,该 id 由 anchor 标记定位,例如:

当我运行此代码时,它会快速转到目标 id,尽管我想使用动画。我该怎么做?

最佳答案

您可以使用 jQuery 实现这一点。

这是执行平滑页面滚动到同一页面上的 anchor 的代码。它内置了一些逻辑来识别那些跳转链接,而不是针对其他链接。

// Select all links with hashes
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});

关于javascript - 如何一次不快速地轻柔滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44394184/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com