html 頁面內錨點定位及跳轉方法總結

來源:互聯網
上載者:User

標籤:oct   flow   滾動   簡單   問題   element   事件   標籤   自己   

 

第一種方法,也是最簡單的方法是錨點用<a>標籤,在href屬性中寫入DIV的id。如下:

<!DOCTYPE html>
<html>
<head>
<style>
div {
height: 800px;
width: 400px;
border: 2px solid black;
}
h2 {
position: fixed;
margin:50px 500px;
}
</style>
</head>
<body>
<h2>
<a href="#div1">to div1</a>
<a href="#div2">to div2</a>
<a href="#div3">to div3</a>
</h2>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
</body>
</html>

這種方法的缺點是點擊錨點之後,瀏覽器的URL會發生變化,如果重新整理可能會出現問題。 

第二種方法是在js事件中通過window.location.hash="divId"跳轉,但地址也會發生變化,感覺跟第一種方法沒區別,甚至更麻煩。

第三種方法是用animate屬性,當點擊錨點後,頁面滾動到相應的DIV。接著上面的代碼,具體添加如下代碼:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#div1Link").click(function() {
$("html, body").animate({
scrollTop: $("#div1").offset().top }, {duration: 500,easing: "swing"});
return false;
});
$("#div2Link").click(function() {
$("html, body").animate({
scrollTop: $("#div2").offset().top }, {duration: 500,easing: "swing"});
return false;
});
$("#div3Link").click(function() {
$("html, body").animate({
scrollTop: $("#div3").offset().top }, {duration: 500,easing: "swing"});
return false;
});
});
</script>

注意:運行上面的指令碼的之前,先將為錨點增加相應的id,同時去掉href屬性。   

$("html, body")可以替換為響應的div,如果不起作用,試著給該div增加overflow:scroll屬性。

另外,指令碼可以進一步最佳化,自己來試試

這樣做的好處是:URL地址不會變,同時點擊錨點時會自動響應scroll事件,不需要重新綁定。

缺點是:如果頁面複雜的話,位移值可能會發生變化需要演算法輔助。


第四種方法是用js的srollIntoView方法,直接用:
document.getElementById("divId").scrollIntoView();
這種方法的好處,是URL不會變,同時能夠響應相應的scroll事件,不需要演算法什麼的。

推介大家用第四種,我依次試了前三種,都有各種問題。

 

html 頁面內錨點定位及跳轉方法總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.