簡體   English   中英

使用 URL 中不帶 # 的錨點滾動

[英]Scroll with anchor without # in URL

我需要使用anchor tag<\/code>滾動頁面。

現在我正在做:

<a href="#div1">Link1</a>

<div id='div1'>link1 points me!!</div>

從Jeff Hines的jQuery動畫中獲得以下答案:

function goToByScroll(id){
    $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}

如果您使用的是jQuery,請不要忘記將庫添加到項目中。

編輯:另外,請確保您仍然“返回false;”。 在鏈接的點擊處理程序中,否則仍將“#div1”添加到您的網址中(感謝@niaccurshi)

當所有其他方法都失敗時, scrollIntoView表現最佳!

document.getElementById('top').scrollIntoView(true);

其中'top'是您要使用的html標簽的ID。

讓您的生活更輕松,嘗試以下方法,讓我知道是否還有其他問題;-)

<div>top</div>
<div style="height: 800px;">&nbsp;</div>
<div><a href="javascript:void(0);" onclick="window.scroll(0,1);">click here</a></div>

僅供參考:您只需要使用單行href="javascript:void(0);" onclick="window.scroll(0,1);" href="javascript:void(0);" onclick="window.scroll(0,1);" 它為您服務。

祝你有美好的一天!

僅在准備好文檔時將此代碼添加到jquery中

參考: http : //css-tricks.com/snippets/jquery/smooth-scrolling/

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

弄清Henser 的答案 ,我有一個情況是window.location.hash已經設置好,然后用戶滾動回到頁面頂部(哈希鏈接所在的位置)。

由於已經設置了哈希,因此可以通過以下方式單擊該鏈接來重新定位:

$(window).scrollTop($('a[name='+id+']').offset().top);

我知道我遲到了4年,但是你們可以嘗試一下。

HTML:

<a href="#div1">Link1</a>
<!-- you can put <br />'s here to see effect -->
<div id='div1'>link1 points me!!</div>
<!-- <br />'s here, too, to see effect -->

JavaScript / jQuery

$(document).ready(function(){
    $('a').on('click', function(event) {
        event.preventDefault();
        var hash = this.hash;
        $('html, body').animate({scrollTop: $(hash).offset().top}, 900);
    });
})

將平滑滾動添加到任何項目單擊(包括錨,按鈕等),而無需將div id添加到URL :)

信息: scrollIntoViewOptions(可選) {行為:“自動” | “即時” | “平滑”,塊:“開始” | “結束”, }

 function scrollSmoothTo(elementId) { var element = document.getElementById(elementId); element.scrollIntoView({ block: 'start', behavior: 'smooth' }); } 
 #userdiv { margin-top: 200px; width: 200px; height: 400px; border: 1px solid red; } 
 <button onclick="scrollSmoothTo('userdiv')"> Scroll to userdiv </button> <div id="userdiv"> Lorem ipsum this is a random text </div> 

演示

參考: https : //developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView

document.getElementById('top').scrollIntoView(true);

應該適用於所有瀏覽器,經過測試!

暫無
暫無

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

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