頁面內跳轉到相應位置的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距離文檔頂部的距離,再使頁面滾動到這個高度來達到目的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM