首页 > 编程 > JavaScript > 正文

页面内锚点定位及跳转方法总结(推荐)

2019-11-19 11:42:43
字体:
来源:转载
供稿:网友

接着上一篇,其实是一个功能,本来感觉挺简单的一个问题,没想到遇到两个坎儿,无语。。。

上一篇是关于scroll事件绑定的问题,这一篇的问题是:点击锚点跳转到相应DIV的问题。

最简单的方法是锚点用<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" rel="external nofollow" >to div1</a>    <a href="#div2" rel="external nofollow" >to div2</a>    <a href="#div3" rel="external nofollow" >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"><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方法,直接用:

document.getElementById("divId").scrollIntoView();

这种方法的好处,是URL不会变,同时能够响应相应的scroll事件,不需要算法什么的。

推介大家用第四种,我依次试了前三种,都有各种问题(可能是页面较复杂的缘故吧,当然,技术不咋也是。。。)  

以上所述是小编给大家介绍的页面内锚点定位及跳转方法总结详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表