我有一些很長的頁面。在頁腳中,我有一個錨鏈接將用戶帶回頁眉。我希望能夠使用以下 CSS(但它在 Safari 中不起作用)使滾動平滑(減慢速度)。
html {
scroll-behavior: smooth;
}
所以我找到了一些 JQuery。我不懂 JQuery,有一些問題。
$(document).ready(function(){
// Add smooth scrolling to all links
$("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
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
- 有沒有可能使這更簡單?
2.我不確定是否需要將#top 添加到 URL?我想讓頁面做的就是回到頂部(我沒有使用錨鏈接導航到一些內容)。但我不知道如何在不破壞整個事情的情況下洗掉此代碼。我試過了,不知道該洗掉什么,保留什么。
- “確保 this.hash 具有值”是什么意思。我忽略了它,它似乎作業正常。
更新
這是我的 HTML(顯然在頁眉和頁腳之間有很多內容)
<header id="top">.... </header>
<footer>
<a href="#top"><img class="to-top" src="resources/arrow.svg"></a>
</footer>
uj5u.com熱心網友回復:
如果您僅將 JQuery 用于此功能,請使用JavaScript 中的scrollIntoView。
有了JQuery,這個功能就夠了:
function elevator(where) {
var the_id = "#" where;
$('html, body').animate({
scrollTop:$(the_id).offset().top
}, 'slow');
return false;
}
您可以在這樣的 html 標簽中使用它:
<h1 id="title">Title at the top of the page</h1>
<!-- a lot of space -->
<button onclick="elevator('title')">go up</button>
注意: CSS 屬性對這個函式沒有用。
現在,如果你想解釋你的代碼:
$(document).ready(function(){
// Add smooth scrolling to all links
// i.e. select all links on your page and add en event for each of them
// event called when there is a click
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
// the hash is the anchor. For example: "website.com/page.html#hash"
// we must check if there is an hash in the link
if (this.hash !== "") {
// Prevent default anchor click behavior
// i.e. the default behavior of a link
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
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
您的代碼正在自動為每個鏈接創建平滑效果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381006.html
標籤:javascript html 查询
下一篇:Mousedown內部的點擊問題
