Javascript使用元素下移滚动条不起作用

时间:2019-04-09 21:14:18

标签: javascript css css3 scrollbar

嘿,我下面有全部html代码,应该,当您按下按钮时,允许页面一直滚动到 nextChatHolder 元素。

它在底部添加了聊天气泡,但是每次我按下按钮时,我希望它向下滚动到 nextChatHolder

我没有错误,这些示例可以独立运行。因此,很自然地在我的javascript或css某处导致其无法滚动-我无法找到它的内容!

视觉:https://jsbin.com/xihosicayo/edit?js,output

function getElementY(query) {
        return window.pageYOffset + document.querySelector(query).getBoundingClientRect().top;
    }

    function scrollToItem(item) {
        var diff = (item.offsetTop-window.scrollY)/8;

        if (Math.abs(diff) > 1) {
            window.scrollTo(0, (window.scrollY+diff));
            clearTimeout(window._TO);
            window._TO=setTimeout(scrollToItem, 30, item);
        } else {
            window.scrollTo(0, item.offsetTop);
        }
    }

    function doScrolling(element, duration) {
        var startingY   = window.pageYOffset
        var elementY    = getElementY(element)
        var targetY     = document.body.scrollHeight - elementY < window.innerHeight ? document.body.scrollHeight - window.innerHeight : elementY
        var diff        = targetY - startingY
        var easing      = function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1; }
        var start;

        if (!diff) return
            window.requestAnimationFrame(function step(timestamp) {     
                if (!start) start = timestamp;
                var time = timestamp - start;
                var percent = Math.min(time / duration, 1);

                percent = easing(percent);
                window.scrollTo(0, startingY + diff * percent);

                if (time < duration) {
                    window.requestAnimationFrame(step);
                }
            })
        }

    function newTalk(textVal, pic) {
        var my_elem = document.getElementById("nextChatHolder");
        var div = document.createElement('div');

        div.innerHTML = '<div class="animated animatedFadeInUp fadeInUp">' +
                            '<div class="chat self">' +
                                '<div class="user-photo">' +
                                    '<img src="' + pic + '">' +
                                '</div>' +
                                '<p class="chat-message">' + textVal + '</p>' +
                                '<span class="timeself">11:01 PM | Oct 11 2019</span>' +
                            '</div>' +
                        '</div>';

        my_elem.parentNode.insertBefore(div, my_elem);
        //scrollToItem(my_elem))
    }

1 个答案:

答案 0 :(得分:0)

我相信您正在寻找:

my_elem.scrollIntoView({behavior: "smooth",block: "end"})

作为newTalk的最后一行。

Documentation