Jquery - 滚动到数据 ID

Jquery - Scroll to data-id

我有一个 div,其数据参数 'go' 包含页面下方 div 的 ID。例如:

<div data-go="help" data-info="">text</div>

目前,我可以使用以下代码跳转到 div:

$("#icons > div").click(
    function() {
        input = $(this).data("go");
        window.location.hash = input;
    }
);

不过,我想要一个平滑的过渡(scrollto)。
我尝试调整各种 Whosebug 解决方案 - 但到目前为止运气不好。

参见 this JSFiddle:

JavaScript

$("#icons > div").click(
    function() {
        var id = $(this).data("go");
        $(document.body).animate({scrollTop: $("#" + id).offset().top, duration: 400});
    }
);

HTML

<div id="icons">
    <div data-go="help" data-info="">text</div>
</div>

<div id="help">
    <h1>
        Help section
    </h1>
</div>

获取 body 的顶部 offset position value of the target element, then use jQuery's animate function to animate the scrollTop 属性:

var input = $(this).data("go");
jQuery(document.body).animate({
   scrollTop:jQuery("#"+input).offset().top+"px"
});

演示

$("#text").click(function() {    
    var input = $(this).data("go");
    var top = jQuery("#"+input).offset().top;
    jQuery(document.body).animate({
       scrollTop:top+"px"
    },1000);
});
#spacer {
  height:1500px;
}
#help {
  height:250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="text" data-go="help" data-info="">text</div>
<div id="spacer"></div>
<div id="help">Help</div>