html页面内锚点定位显示

来源:互联网 发布:淘宝客服外包协议 编辑:程序博客网 时间:2024/05/29 17:02

html页面内锚点定位跳转


     html页面页面中经常会有点击页面的导航图标定位显示到

     未在屏幕显示的页面。


     如图所示:

    

    

      实现方法:

      1. 用<a>标签设置锚点,在href属性中写入DIV的id。如下:

     

<!DOCTYPE html><html><head><style>div {height: 800px;width: 400px;border: 1px 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会发生变化,如果刷新可能会出现问题。 

   

    2. 用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>

    这样做的好处是:URL地址不会变,同时点击锚点时会自动响应scroll事件,不需要重新绑定。

   缺点是:如果页面复杂的话,偏移值可能会发生变化需要算法辅助。

    3.js的srollIntoView方法,直接用页面定位显示到相应的位置:
     document.getElementById("divId").scrollIntoView();
     这种方法的好处,是URL不会变,同时能够响应相应的scroll事件,没有复杂的算法

     缺点:跳转效果单一。

   

1 0
原创粉丝点击