平滑滚动锚链接没有jQuery [英] Smooth scroll anchor links WITHOUT jQuery

查看:136
本文介绍了平滑滚动锚链接没有jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用平滑滚动来锚定链接,但没有 jQuery ?我正在创建一个新网站,我不想使用 jQuery

Is it possible to use smooth scroll to anchor links but without jQuery? I am creating a new site and I don't want to use jQuery.

推荐答案

使用此处的功能: JavaScript动画并修改它以修改属性(不仅仅是样式的属性),你可以尝试这样的事情:

Using the function from here: JavaScript animation and modifying it to modify a property (not only a style's property), you can try something like this:

function animate(elem, style, unit, from, to, time, prop) {
    if (!elem) {
        return;
    }
    var start = new Date().getTime(),
        timer = setInterval(function () {
            var step = Math.min(1, (new Date().getTime() - start) / time);
            if (prop) {
                elem[style] = (from + step * (to - from))+unit;
            } else {
                elem.style[style] = (from + step * (to - from))+unit;
            }
            if (step === 1) {
                clearInterval(timer);
            }
        }, 25);
    if (prop) {
          elem[style] = from+unit;
    } else {
          elem.style[style] = from+unit;
    }
}

window.onload = function () {
    var target = document.getElementById("div5");
    animate(document.scrollingElement || document.documentElement, "scrollTop", "", 0, target.offsetTop, 2000, true);
};

DEMO: https://jsfiddle.net/zpu16nen/

确保将窗口调整得足够小,以便实际上一个滚动条,可以滚动到第5个div。

Make sure you size the window small enough so there's actually a scrollbar and can scroll to the 5th div.

不,它不需要重新创建25%的jQuery。

And no, it didn't require the recreation of 25% of jQuery.

这显然需要高度修改,具体取决于你的问题实际意味着什么(比如当窗口哈希发生变化时,或类似的东西)。

This would obviously needly highly modified depending on what your question actually means (like when the window hash changes, or something like that).

注意使用jQuery,它很简单:

Note that with jQuery, it's as easy as:

$(document).ready(function () {
    $("html, body").animate({
        scrollTop: $("#div5").offset().top
    }, 2000);
});

DEMO: http://jsfiddle.net/7TAa2/1/

只是说...

这篇关于平滑滚动锚链接没有jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆