簡體   English   中英

平滑滾動到名稱和ID

[英]smooth scroll to name and ID

我有這段代碼可以平滑滾動到div ID,但不能滾動到名稱:

$('.scroll').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top - 70
    }, 800, function(){
        window.location.hash = "#";
        return false;
    });
});

而與此相反:

$('.scroll').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top - 70
    }, 800, function(){
        window.location.hash = "#";
        return false;
    });
});

如何在一個代碼中混合使用兩種代碼來滾動到ID和名稱?

加入選擇器。 這樣,jQuery將使用它找到的第一個:

        scrollTop: $($.attr(this, 'href') + ',[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top - 70

萬一有人需要它:

$(function() {
    $('.scroll').on('click', function(e) {
        e.preventDefault();
        $('html, body').animate({
            scrollTop: $($.attr(this, 'href') + ',[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top - 70
        }, 800, function(){
            window.location.hash = ="#";
            return false;
        });
    });
});

有沒有辦法用香草javascript做到這一點?

我發現在香草javascript中執行此操作的最佳解決方案是導入包https://github.com/cferdinandi/smooth-scroll

我不確定我是否100%理解了您的問題,但我認為您可以使用querySelector按名稱搜索元素,然后以這種方式將滾動應用於您的元素。

我之前在尋找一種簡單的滾動解決方案,遇到了scrollIntoView 與我發現的任何其他解決方案一樣,它的魅力十足,並且所需的代碼少得多。

 var foo = document.querySelector('[name="foo"]'); var bar = document.querySelector('#bar'); foo.addEventListener('click', function(){ bar.scrollIntoView({behavior: 'smooth', block: 'start'}); }); 
 .top { width: 100%; height: 150vh; background-color: blue; text-align: center } button { margin-top: 2rem; padding: 5px 15px; font-size 18px; } .second { display: flex; justify-content: center; width: 100%; height: 100vh; background-color: green; } h1 { color: white; } 
 <div class="top"> <button name="foo">Click Here</button> </div> <div class="second" id="bar"> <h1>It's Working!</h1> </div> 

暫無
暫無

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

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