簡體   English   中英

單擊錨鏈接時平滑滾動

[英]Smooth scrolling when clicking an anchor link

我的頁面上有幾個超鏈接。 用戶訪問我的幫助部分時會閱讀的常見問題解答。

使用錨鏈接,我可以使頁面滾動到錨點並引導用戶到那里。

有沒有辦法使滾動平滑?

但請注意,他使用的是自定義 JavaScript 庫。 也許 jQuery 提供類似這樣的東西?

2018 年 4 月更新:現在有一種本地方法可以做到這一點

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

這目前僅在最前沿的瀏覽器中受支持。


對於較舊的瀏覽器支持,您可以使用以下 jQuery 技術:

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

這是小提琴: http : //jsfiddle.net/9SDLw/


如果您的目標元素沒有 ID,並且您通過其name鏈接到它,請使用以下命令:

$('a[href^="#"]').click(function () {
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 500);

    return false;
});

為了提高性能,您應該緩存$('html, body')選擇器,這樣它就不會在每次單擊錨點運行:

var $root = $('html, body');

$('a[href^="#"]').click(function () {
    $root.animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);

    return false;
});

如果您希望更新 URL,請在animate回調中執行此操作:

var $root = $('html, body');

$('a[href^="#"]').click(function() {
    var href = $.attr(this, 'href');

    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });

    return false;
});

正確的語法是:

//Smooth scrolling with links
$('a[href*=\\#]').on('click', function(event){     
    event.preventDefault();
    $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});

// Smooth scrolling when the document is loaded and ready
$(document).ready(function(){
  $('html,body').animate({scrollTop:$(location.hash).offset().‌​top}, 500);
});

簡化:干

function smoothScrollingTo(target){
  $('html,body').animate({scrollTop:$(target).offset().​top}, 500);
}
$('a[href*=\\#]').on('click', function(event){     
    event.preventDefault();
    smoothScrollingTo(this.hash);
});
$(document).ready(function(){
  smoothScrollingTo(location.hash);
});

href*=\\\\#

  • *表示它匹配包含#字符的內容。 因此只匹配anchors 有關此含義的更多信息,請參見此處
  • \\\\是因為#是 css 選擇器中的一個特殊字符,所以我們必須對其進行轉義。

CSS3 中的新熱點。 這比此頁面上列出的每種方法都要容易得多,並且不需要 Javascript。 只需在您的 css 中輸入以下代碼,突然間指向您自己頁面內位置的鏈接將具有平滑的滾動動畫。

html{scroll-behavior:smooth}

之后,指向 div 的任何鏈接都將平滑地滑到這些部分。

<a href="#section">Section1</a>

編輯:對於那些對上述標簽感到困惑的人。 基本上它是一個可點擊的鏈接。 然后你可以在你的網頁中的某個地方有另一個 div 標簽,比如

<div id="section">content</div>

在這方面,a 鏈接將是可點擊的,並將轉到任何 #section,在這種情況下,它是我們稱為 section 的 div。

順便說一句,我花了幾個小時試圖讓它發揮作用。 在一些晦澀的評論部分找到了解決方案。 它有問題,在某些標簽中不起作用。 對身體不起作用。 當我把它放在 CSS 文件的 html{} 中時,它終於奏效了。

只有 CSS

html {
    scroll-behavior: smooth !important;
}

所有你需要添加的只是這個。 現在您的內部鏈接滾動行為將像流一樣流暢。

以編程方式:一些額外和高級的東西

// Scroll to specific values
// window.scrollTo or
window.scroll({
  top: 1000, 
  left: 0, 
  behavior: 'smooth'
});

// Scroll certain amounts from current position 
window.scrollBy({ 
  top: 250, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

// Scroll to a certain element
document.getElementById('el').scrollIntoView({
  behavior: 'smooth'
})

注意:所有最新的瀏覽器( OperaChromeFirefox等)都支持此功能。

詳細了解,請閱讀這篇 文章

$('a[href*=#]').click(function(event){
    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    event.preventDefault();
});

這對我來說很完美

我很驚訝沒有人發布了一個本地解決方案,該解決方案還負責更新瀏覽器位置哈希以進行匹配。 這里是:

let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere 
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}

見教程: http : //www.javascriptkit.com/javatutors/scrolling-html-bookmark-javascript.shtml

對於帶有粘性標題的站點,可以使用scroll-padding-top CSS 來提供偏移量。

不需要任何 js 只需使用 scroll-behavior: smooth at html 標簽就是這樣

html{
scroll-behavior: smooth;
}

我建議你制作這個通用代碼:

$('a[href^="#"]').click(function(){

var the_id = $(this).attr("href");

    $('html, body').animate({
        scrollTop:$(the_id).offset().top
    }, 'slow');

return false;});

你可以在這里看到一篇很好的文章: jquery-effet-smooth-scroll-defilement-fluide

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

官方: http : //css-tricks.com/snippets/jquery/smooth-scrolling/

這里已經有很多好的答案——但是它們都忽略了必須排除空錨點的事實。 否則,一旦單擊空錨點,這些腳本就會生成 JavaScript 錯誤。

在我看來,正確的答案是這樣的:

$('a[href*=\\#]:not([href$=\\#])').click(function() {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

使用 JQuery:

$('a[href*=#]').click(function(){
  $('html, body').animate({
    scrollTop: $( $.attr(this, 'href') ).offset().top
  }, 500);
  return false;
});

有一種使用滾動行為的 css 方法。 添加以下屬性。

    scroll-behavior: smooth;

就是這樣。 不需要JS。

 a { display: inline-block; width: 50px; text-decoration: none; } nav, scroll-container { display: block; margin: 0 auto; text-align: center; } nav { width: 339px; padding: 5px; border: 1px solid black; } scroll-container { display: block; width: 350px; height: 200px; overflow-y: scroll; scroll-behavior: smooth; } scroll-page { display: flex; align-items: center; justify-content: center; height: 100%; font-size: 5em; }
 <nav> <a href="#page-1">1</a> <a href="#page-2">2</a> <a href="#page-3">3</a> </nav> <scroll-container> <scroll-page id="page-1">1</scroll-page> <scroll-page id="page-2">2</scroll-page> <scroll-page id="page-3">3</scroll-page> </scroll-container>

PS:請檢查瀏覽器兼容性。

對哈希 id 滾動的平滑滾動有本機支持。

html {
  scroll-behavior: smooth;
}

你可以看看: https : //www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2

給出的答案有效但禁用傳出鏈接。 在帶有額外獎勵的版本下方緩出(擺動)並尊重傳出鏈接。

$(document).ready(function () {
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

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;
            }
        }
    });
});

如今,現代瀏覽器的速度要快一些。 setInterval 可能會起作用。 這個功能現在在 Chrome 和 Firefox 中運行良好。(在 safari 中有點慢,沒有打擾 IE)

function smoothScroll(event) {
    if (event.target.hash !== '') { //Check if tag is an anchor
        event.preventDefault()
        const hash = event.target.hash.replace("#", "")
        const link = document.getElementsByName(hash) 
        //Find the where you want to scroll
        const position = link[0].getBoundingClientRect().y 
        let top = 0

        let smooth = setInterval(() => {
            let leftover = position - top
            if (top === position) {
                clearInterval(smooth)
            }

            else if(position > top && leftover < 10) {
                top += leftover
                window.scrollTo(0, top)
            }

            else if(position > (top - 10)) {
                top += 10
                window.scrollTo(0, top)
            }

        }, 6)//6 milliseconds is the faster chrome runs setInterval
    }
}

添加這個:

function () {
    window.location.hash = href;
}

以某種方式使垂直偏移無效

top - 72

在 Firefox 和 IE 中,而不是在 Chrome 中。 基本上,頁面會根據偏移量平滑滾動到它應該停止的點,然后向下跳到頁面沒有偏移量的位置。

它確實將散列添加到 url 的末尾,但按回不會將您帶回到頂部,它只是從 url 中刪除散列並將查看窗口留在它所在的位置。

這是我正在使用的完整 js:

var $root = $('html, body');
$('a').click(function() {
    var href = $.attr(this, 'href');
    $root.animate({
        scrollTop: $(href).offset().top - 120
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});

此解決方案也適用於以下 URL,而不會破壞指向不同頁面的錨鏈接。

http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor

./index.html
./index.html#anchor

等等。

var $root = $('html, body');
$('a').on('click', function(event){
    var hash = this.hash;
    // Is the anchor on the same page?
    if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
        $root.animate({
            scrollTop: $(hash).offset().top
        }, 'normal', function() {
            location.hash = hash;
        });
        return false;
    }
});

我還沒有在所有瀏覽器中測試過這個。

這將使 jQuery 能夠輕松識別您的目標哈希並知道何時何地停止。

$('a[href*="#"]').click(function(e) {
    e.preventDefault();
    var target = this.hash;
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});
$("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;

    }



});

經過測試和驗證的代碼

<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>

對於用於平滑滾動的方法更全面的列表,請參閱我的答案在這里


您可以使用具有behavior: smooth window.scroll() behavior: smoothtop設置為錨標記的偏移頂部,以確保錨標記位於視口的頂部。

document.querySelectorAll('a[href^="#"]').forEach(a => {
    a.addEventListener('click', function (e) {
        e.preventDefault();
        var href = this.getAttribute("href");
        var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");
        //gets Element with an id of the link's href 
        //or an anchor tag with a name attribute of the href of the link without the #
        window.scroll({
            top: elem.offsetTop, 
            left: 0, 
            behavior: 'smooth' 
        });
        //if you want to add the hash to window.location.hash
        //you will need to use setTimeout to prevent losing the smooth scrolling behavior
       //the following code will work for that purpose
       /*setTimeout(function(){
            window.location.hash = this.hash;
        }, 2000); */
    });
});

演示:

 a, a:visited{ color: blue; } section{ margin: 500px 0px; text-align: center; }
 <a href="#section1">Section 1</a> <br/> <a href="#section2">Section 2</a> <br/> <a href="#section3">Section 3</a> <br/> <a href="#section4">Section 4</a> <section id="section1"> <b style="font-size: 2em;">Section 1</b> <p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/> <section> <section id="section2"> <b style="font-size: 2em;">Section 2</b> <p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <section> <section id="section3"> <b style="font-size: 2em;">Section 3</b> <p> Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <section> <a style="margin: 500px 0px; color: initial;" name="section4"> <b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b> </a> <p> Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <script> document.querySelectorAll('a[href^="#"]').forEach(a => { a.addEventListener('click', function (e) { e.preventDefault(); var href = this.getAttribute("href"); var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]"); window.scroll({ top: elem.offsetTop, left: 0, behavior: 'smooth' }); }); }); </script>

您可以將 CSS 屬性scroll-behaviorsmooth (大多數現代瀏覽器都支持),這樣就不需要 Javascript。

 html, body{ scroll-behavior: smooth; } a, a:visited{ color: blue; } section{ margin: 500px 0px; text-align: center; }
 <a href="#section1">Section 1</a> <br/> <a href="#section2">Section 2</a> <br/> <a href="#section3">Section 3</a> <br/> <a href="#section4">Section 4</a> <section id="section1"> <b style="font-size: 2em;">Section 1</b> <p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/> <section> <section id="section2"> <b style="font-size: 2em;">Section 2</b> <p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <section> <section id="section3"> <b style="font-size: 2em;">Section 3</b> <p> Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p> <section> <a style="margin: 500px 0px; color: initial;" name="section4"> <b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b> </a> <p> Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea. Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram. Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his. Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat. Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>

我為 "/xxxxx#asdf" 和 "#asdf" href 錨點做了這個

$("a[href*=#]").on('click', function(event){
    var href = $(this).attr("href");
    if ( /(#.*)/.test(href) ){
      var hash = href.match(/(#.*)/)[0];
      var path = href.match(/([^#]*)/)[0];

      if (window.location.pathname == path || path.length == 0){
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 1000);
        window.location.hash = hash;
      }
    }
});

這是我為多個鏈接和錨點實現的解決方案,以實現平滑滾動:

http://www.adriantomic.se/development/jquery-localscroll-tutorial/如果您在導航 div 中設置了導航鏈接並使用以下結構聲明:

<a href = "#destinationA">

以及您相應的錨標記目的地,如下所示:

<a id = "destinationA">

然后只需將其加載到文檔的頭部:

    <!-- Load jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<!-- Load ScrollTo -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>

<!-- Load LocalScroll -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>

<script type = "text/javascript">
 $(document).ready(function()
    {
        // Scroll the whole document
        $('#menuBox').localScroll({
           target:'#content'
        });
    });
</script>

感謝@Adriantomic

如果頁面上有一個簡單的按鈕可以向下滾動到 div 並且希望后退按鈕通過跳到頂部來工作,只需添加以下代碼:

$(window).on('hashchange', function(event) {
    if (event.target.location.hash=="") {
        window.scrollTo(0,0);
    }
});

這也可以擴展到跳轉到不同的 div,通過讀取哈希值,並像 Joseph Silbers 回答一樣滾動。

永遠不要忘記 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() 函數總是會給你不同的位置值。

感謝分享,約瑟夫·西爾伯。 這里你的 2018 解決方案作為 ES6 進行了微小的更改以保持標准行為(滾動到頂部):

document.querySelectorAll("a[href^=\"#\"]").forEach((anchor) => {
  anchor.addEventListener("click", function (ev) {
    ev.preventDefault();

    const targetElement = document.querySelector(this.getAttribute("href"));
    targetElement.scrollIntoView({
      block: "start",
      alignToTop: true,
      behavior: "smooth"
    });
  });
});

需要 jquery 和 animates 使用指定的名稱而不是 id 來錨定標簽,同時將哈希添加到瀏覽器 url。 還使用 jquery 修復了大多數答案中的錯誤,其中 # 符號沒有以轉義反斜杠為前綴。 不幸的是,后退按鈕無法正確導航回以前的哈希鏈接...

$('a[href*=\\#]').click(function (event)
{
    let hashValue = $(this).attr('href');
    let name = hashValue.substring(1);
    let target = $('[name="' + name + '"]');
    $('html, body').animate({ scrollTop: target.offset().top }, 500);
    event.preventDefault();
    history.pushState(null, null, hashValue);
});

好吧,解決方案取決於問題的類型,我使用 javascript 動畫方法來單擊按鈕。 我使用來自導航欄的波紋管鏈接的代碼

https://css-tricks.com/snippets/jquery/smooth-scrolling/

$(document).ready(function () {
  $(".js--scroll-to-plans").click(function () {
    $("body,html").animate(
      {
        scrollTop: $(".js--section-plans").offset().top,
      },
      1000
    );
    return false;
  });

  $(".js--scroll-to-start").click(function () {
    $("body,html").animate(
      {
        scrollTop: $(".js--section-features").offset().top,
      },
      1000
    );
    return false;
  });

  $('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
          };
        });
      }
    }
  });
});

對於正在尋找 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM