有没有办法滚动到锚点而不是用javascript跳转(类似于平滑滚动)

Is there way to scroll to anchor rather than jump with javascript (something like smooth scroll)

本文关键字:滚动 跳转 javascript 类似于 平滑 有没有      更新时间:2023-09-26

我有一个大文档,上面有编号的锚标记,如下所示。以及一个文本框,用于将数字输入到使用window.location.hash的锚点

我还使用箭头键转到下一个或上一个锚点。我想滚动到锚,以便给一些方向感。

<a name="1">
some text
<a name="2">
some text
<a name="3">

这是我的功能

function updatePageNumber()
{
    var pagenumber;
    pagenumber = document.getElementById('pageNumber').value;   
    window.location.hash =  pagenumber;
}

跳锚是非常丑陋的,人们在文本中失去了方向感。那么,有没有一种方法可以使用JavaScript滚动到锚点。我知道有很多jQuery的例子,但我不知道jQuery,也找不到JavaScript。

最重要的原因是我想在地址栏上看到我的页码!

添加jQuery库。

使用以下脚本平滑滚动到所需的目标元素。

jQuery('html,body').animate({scrollTop: jQuery('#target').offset().top}, 1000);

target是目标元素的id,1000是动画的持续时间。

使用此代码并享受

$(document).ready(function(){
$("#btop").hide();  // replace only #btop with your <div id=" ">
$(function(){
    $(window).scroll(function(){
        if ($(this).scrollTop()>100){
            $('#btop').fadeIn();  // replace only #btop with your <div id=" ">
        }
        else{
            $('#btop').fadeOut(); // replace only #btop with your <div id=" ">
        }
    });
    $('#btop a').click(function(){ // replace only #btop with your <div id=" ">
        $('body,html').animate({
          scrollTop:0
        },200);  // to speed up scroll replace 200 to 300 or 500
        return false;
    });
});
});

JavaScript中没有内置的平滑滚动,所以你必须自己实现它——但是,如果你在jQuery中已经有了轮子,而且你可能不需要添加超过两三行的代码,为什么要重新发明轮子呢?只需下载jQuery和ScrollTo插件,将它们添加到<script>标签中的<head>部分,然后使用它滚动到具有给定ID:的元素

$.scrollTo("#my-element-id");

这将滚动到ID为my-element-id的元素,因此您必须在锚点中使用id=...属性,而不是name=...属性。

如果你想将这种行为自动添加到给定div内的所有锚点(或整个页面),你可以使用LocalScroll插件,它使整个过程变得简单:

$.localScroll();