錨點定位及跳轉方法總結
阿新 • • 發佈:2018-12-31
1 js控制錨點跳轉 <a name="anchor"></a> location.hash="anchor"; 不只有a其他元素也可以,比如在報表中: <tr id="tr1">...</tr> location.hash="tr1" 或者用jQuery的動畫滾動效果: var id="tr1"; $('html,body').animate({scrollTop: $("tr#"+id).offset().top}, 500); 2 html控制錨點跳轉 <a href="#btn">跳轉到點選位置</a> <a name="btn" id="btn" > 點選</a> 3跨頁面錨點跳轉 程式碼如下 <a href="123.html#btn">跳到btn</a> <a name="btn" id="btn" > </a> 4js控制錨點跳轉在HTML中實現方式 <div id="divNode"><!-- contents --></div><!-- 假設一個需要跳轉到的節點 --> <a href="#" onclick="document.getElemetnById('divNode').scrollIntoView(true);return false;">通過scrollIntoView實現錨點效果</a>
<!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。接著上面的程式碼,具體新增如下程式碼:
12 | < script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></ script > < script type="text/javascript">< br >$(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;
});
});
1 | </ script > |
注意:執行上面的指令碼的之前,先將為錨點增加相應的id,同時去掉href屬性。
$("html, body")可以替換為響應的div,如果不起作用,試著給該div增加overflow:scroll屬性。
另外,指令碼可以進一步優化,自己來試試
這樣做的好處是:URL地址不會變,同時點選錨點時會自動響應scroll事件,不需要重新繫結。
缺點是:如果頁面複雜的話,偏移值可能會發生變化需要演算法輔助。
第四種方法是用js的srollIntoView方法,直接用:
1 | document.getElementById( "divId" ).scrollIntoView(); |
這種方法的好處,是URL不會變,同時能夠響應相應的scroll事件,不需要演算法什麼的。
推介大家用第四種,我依次試了前三種,都有各種問題(可能是頁面較複雜的緣故吧,當然,技術不咋也是。。。)