【问题标题】:Is there way to scroll to anchor rather than jump with javascript (something like smooth scroll)有没有办法滚动到锚点而不是用javascript跳转(比如平滑滚动)
【发布时间】:2014-09-16 08:51:49
【问题描述】:

我有一个带有编号锚标记的大型文档,如下所示。还有一个文本框,用于输入数字以转到使用 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。

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

【问题讨论】:

标签: javascript scroll anchor


【解决方案1】:

添加 jQuery 库。

使用以下脚本平滑滚动到您想要的目标元素。

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

target是目标元素的id,1000是动画的时长。

【讨论】:

  • 不是要恢复一个老问题,你的解决方案中有一个错误;您需要引用 offset 对象的 top,而不是偏移量本身。换句话说:jQuery('html,body').animate({scrollTop: jQuery('#target').offset().top}, 1000);
  • 我冒昧地应用了@ean5533 的错误修复,因为它是正确的。首先,我只是复制/粘贴了答案的代码;没用。大坝,开始寻找别的东西。后来看到评论。 Ups,它有效!
【解决方案2】:

使用此代码并享受乐趣

$(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;
    });
});
});

【讨论】:

    【解决方案3】:

    JavaScript 中没有内置的平滑滚动,因此您必须自己实现它——但是如果您已经在 jQuery 中拥有它,为什么还要重新发明轮子,而且您可能不需要添加更多两三行代码?只需下载 jQuery 和 ScrollTo plugin,将它们添加到 &lt;script&gt; 标签中的 &lt;head&gt; 部分,然后使用它滚动到具有给定 ID 的元素:

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

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

    如果您希望将此行为自动添加到给定 div 内的所有锚点(或添加到整个页面),您可以使用 LocalScroll plugin,这使得整个操作变得如此简单:

    $.localScroll();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 2013-07-17
      • 2018-01-19
      • 1970-01-01
      相关资源
      最近更新 更多