【问题标题】:scrollTop() is not working in mobile view or mobile devicesscrollTop() 在移动视图或移动设备中不起作用
【发布时间】:2017-11-02 10:25:57
【问题描述】:

我想在页面加载时滚动到 div 的底部。我正在使用 jQuery 的 animate() 函数。问题是我的代码在桌面视图上运行,但如果我将其更改为移动视图,那么我的代码将无法运行。

$(".chat-msg-list").animate({
  scrollTop: $(".chat-msg-list").prop("scrollHeight")
}, 1000);

【问题讨论】:

  • 问题是出现在桌面浏览器的移动视图还是移动设备的浏览器中?
  • @gypsyCoder 问题出现在桌面浏览器或移动设备浏览器中
  • 你可以试试这个:stackoverflow.com/a/14422360/2805075

标签: javascript jquery


【解决方案1】:

jQuery:

$(".chat-msg-list").animate({
        scrollTop: $(".chat-msg-list").offset().top},
}, 1000);

Javascript:

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

function doScrolling(element, duration) {
    var startingY = window.pageYOffset
    var elementY = getElementY(element)
    // If element is close to page's bottom then window will scroll only to some position above the element.
    var targetY = document.body.scrollHeight - elementY < window.innerHeight ? document.body.scrollHeight - window.innerHeight : elementY
    var diff = targetY - startingY
    // Easing function: easeInOutCubic
    // From: https://gist.github.com/gre/1650294
    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

    // Bootstrap our animation - it will get called right before next frame shall be rendered.
    window.requestAnimationFrame(function step(timestamp) {
        if (!start) start = timestamp
        // Elapsed miliseconds since start of scrolling.
        var time = timestamp - start
            // Get percent of completion in range [0, 1].
        var percent = Math.min(time / duration, 1)
        // Apply the easing.
        // It can cause bad-looking slow frames in browser performance tool, so be careful.
        percent = easing(percent)

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

            // Proceed with animation as long as we wanted it to.
        if (time < duration) {
          window.requestAnimationFrame(step)
        }
    })
}

//Apply event handlers. Example of firing the scrolling mechanism.
doScrolling('#section1', 1000)

【讨论】:

    猜你喜欢
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多