Skip to content

Instantly share code, notes, and snippets.

@luobotang
Created October 25, 2017 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luobotang/c8b9c97e556149dfbd18b6a3caef5231 to your computer and use it in GitHub Desktop.
Save luobotang/c8b9c97e556149dfbd18b6a3caef5231 to your computer and use it in GitHub Desktop.
将元素移动到屏幕可见范围内
function scrollElementIntoView(el, offsetTop) {
var doc = document.documentElement
var docScrollTop = doc.scrollTop || 0
var viewportHeight = window.innerHeight
var rect = el.getBoundingClientRect()
if (rect.top < 0 || rect.top + rect.height > docScrollTop + viewportHeight) {
var elOffsetTop = (rect.top + docScrollTop)
var newScrollTop = elOffsetTop - (offsetTop > 0 ? offsetTop : (rect.height > viewportHeight ? 0 : (viewportHeight - rect.height) / 2))
doc.scrollTop = newScrollTop
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment