Created
October 25, 2017 10:38
-
-
Save luobotang/c8b9c97e556149dfbd18b6a3caef5231 to your computer and use it in GitHub Desktop.
将元素移动到屏幕可见范围内
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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