页面内跳转到相应位置的3种方法

首先设置所需的css和html

设置css

        .demo{
            width: 200px;
            height: 200px;
            border: 1px red solid;
            margin-bottom: 100px;
            margin-right: 50px;
        }
        .btn{
            position: fixed;
            right: 0;
            top: 20px;
            background-color: #0000cc;
            color: #ffffff;
        }

设置html

<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo" id="demo">这个DIV,id是demo</div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>
<div class="demo"></div>

重点来了

1.第一种方法直接在html中添加

<!--1.使用a标签跳转到对应id的位置-->
<a href="#demo">跳到id为demo的DIV</a>

  使用a标签跳转到相应id的位置

2.第二种方法先在html中添加

<!--2.通过btn的window.location.hash  跳转到对应位置-->
<input  type="button" value="跳到id为demo的DIV"  onclick="javascript:onTopClick();" />

  再添加js代码

    function onTopClick() {
        window.location.hash = "#domo";
    }

  由于btn没有herf跳转功能,这里我们用hash(锚链接)跳到当前页面的位置

3.第三种方法先在html中添加

<button class="btn"> 到指定滚动高度</button>

  再添加js代码

$(document).on('click',$('.btn'),function(){
        $(window).scrollTop($('#demo').offset().top)
    })

  这里我是通过先得到id为demo的div距离文档顶部的距离,再使页面滚动到这个高度来达到目的。

猜你喜欢

转载自www.cnblogs.com/yefanhua/p/9224501.html