2013-03-05 31 views
17

我需要使用anchor tag滾動瀏覽頁面。在網址中使用不帶#的#號滾動滾動條

現在我做:

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

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

當我點擊鏈接1,頁面滾動到ID爲「DIV1」的DIV這工作得很好。
重點是,我不想改變我的網址,當我點擊Link1時,需要以#div作爲後綴。

我試着用錨HREF作爲

void(0); 

location.hash='#div1'; 
return false; 

e.preventdefault; 

如何避免更改URL?

回答

33

採取從傑夫·海因斯這個答案使用jQuery的動畫:

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

如果你正在使用jQuery不要忘了將庫添加到您的項目。

編輯:此外,請確保您仍然「返回false」;在鏈接的點擊處理程序中,否則它仍然會將「#div1」添加到您的URL(謝謝@niaccurshi)

+5

此外,還要確保在該鏈接的點擊處理程序,你仍然 「返回false」,否則仍然會添加「# div1「到您的網址 – niaccurshi 2013-03-05 11:51:59

+1

非常感謝:)這是幫助完整 – mayank 2013-03-05 13:14:08

+0

這很好。在舊的#anchor標籤上花了一大堆時間,但當有一堆腳本時,它們似乎會「破碎」。 – 2017-02-20 18:55:02

3

讓您的生活更輕鬆,嘗試以下並讓我知道是否還有其他內容; )

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

FYI:你只需要玩一個/單線href="javascript:void(0);" onclick="window.scroll(0,1);",它爲你工作。

有一個好的一天!

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

riffing關閉henser的回答,我有其中window.location.hash已經設置的情況下,用戶然後滾動回頁面頂部(哈希鏈接所在的位置)。

由於哈希已設置,您可以通過點擊該鏈接重新定位:

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

12

scrollIntoView做了最好的工作,當所有其他方法失敗!

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

其中'top'是你想要去的html標籤的id。

-1

我知道我遲到了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); 
    }); 
}) 
+0

這真的很糟糕。正如您點擊** ANY **錨標籤時所寫的,您將初始化此功能。你應該定位一個特定的ID。另外,您的解決方案不起作用。 – JGallardo 2017-09-18 23:33:10