滚动按键(回车)

时间:2016-11-21 18:16:17

标签: javascript scroll onkeypress

我正在尝试让我的代码在按键上滚动(输入键13)以滚动到某个部分。我甚至更喜欢当用户键入'launch'(有或没有按下回车键)时,它会滚动到下一部分。目前,它仅在按两次回车键后滚动。

(function ($) {
    document.getElementById("launch").addEventListener("keypress", enterKey);
    function enterKey(e) {
        if (e.keyCode == 13) {
            getInfo();
        }
    } false;

    function getInfo() {
        window.smoothScroll = function (target) {
            var scrollContainer = target;
            do { //find scroll container
                scrollContainer = scrollContainer.parentNode;
                if (!scrollContainer) return;
                scrollContainer.scrollTop += 1;
            } while (scrollContainer.scrollTop == 0);

            var targetY = 0;
            do { //find the top of target relatively to the container
                if (target == scrollContainer) break;
                targetY += target.offsetTop;
            } while (target = target.offsetParent);

            scroll = function (c, a, b, i) {
                i++; if (i > 30) return;
                c.scrollTop = a + (b - a) / 30 * i;
                setTimeout(function () { scroll(c, a, b, i); }, 5);
            }
            // start scrolling
            scroll(scrollContainer, scrollContainer.scrollTop, targetY, 0);
        }
    }

0 个答案:

没有答案