[英]Slow down an html anchor link
我在其他網站上看到過這個非常酷的功能,但我自己似乎找不到。
我想通過錨標記滾動鏈接到頁面的不同部分,而不僅僅是跳轉到所需的 id。 我想一個 javascript 文件可能會有所幫助,或者可能是一個 css 過渡,但我不知道它會是那個過渡元素。
<a href="#bottom">scroll to bottom</a>
<p id="bottom">bottom</p>
謝謝 :)
一些 css 為我完成了這項工作:
html { scroll-behavior: smooth; }
我在這里找到了更多有用的信息:
由於沒有人真正回答過這個問題,我將用我的發現為需要它的人回答。
你所要做的就是像這樣的普通錨鏈接
<a href="#bottom">scroll to bottom</a>
<p id="bottom">bottom</p>
然后添加此 Javascript 代碼,如果您需要更改任何內容,請查看 javascript 注釋
<script>
$(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
// Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
$('a[href*=#]').each(function() {
// Ensure it's a same-page link
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
// Ensure target exists
var $target = $(this.hash), target = this.hash;
if (target) {
// Find location of target
var targetOffset = $target.offset().top;
$(this).click(function(event) {
// Prevent jump-down
event.preventDefault();
// Animate to target
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
// Set hash in URL after animation successful
location.hash = target;
});
});
}
}
});
// Use the first element that is "scrollable" (cross-browser fix?)
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.