是否有window.scrollTo的回调? [英] Is there a callback for window.scrollTo?

查看:1353
本文介绍了是否有window.scrollTo的回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在寡妇滚动后在输入上调用 focus()。我正在使用 scrollTo()方法的平滑行为。问题是焦点方法削减了平滑行为。解决方案是在滚动结束后调用焦点函数。

I want to call focus() on an input after the widow scrolled. I'm using the smooth behavior for the scrollTo() method. The problem is the focus method cut the smooth behavior. The solution is to call the focus function just after the scroll end.

但是我找不到任何关于如何检测 scrollTo 方法结束的文档或主题。

But I can't find any doc or threads speaking about how to detect the end of scrollTo method.

let el = document.getElementById('input')
let elScrollOffset = el.getBoundingClientRect().top
let scrollOffset = window.pageYOffset || document.documentElement.scrollTop
let padding = 12
window.scrollTo({
  top: elScrollOffset + scrollOffset - padding,
  behavior: 'smooth'
})
// wait for the end of scrolling and then
el.focus()

任何想法?

推荐答案

我找到了实现我想要的方法,但我觉得它有点笨拙,不是吗?

I found a way to achieve what I want but I think it's a bit hacky, isn't it?

let el = document.getElementById('input')
let elScrollOffset = el.getBoundingClientRect().top
let scrollOffset = window.pageYOffset || document.documentElement.scrollTop
let padding = 12
let target = elScrollOffset + scrollOffset - padding
window.scrollTo({
  top: target,
  behavior: 'smooth'
})
window.onscroll = e => {
  let currentScrollOffset = window.pageYOffset || document.documentElement.scrollTop
  // Scroll reach the target
  if (currentScrollOffset === target) {
    el.focus()
    window.onscroll = null // remove listener
  }
}

这篇关于是否有window.scrollTo的回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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