Last active
March 31, 2020 13:52
-
-
Save Subilan/30945009fef38fafd6fe35c8458b6b8d to your computer and use it in GitHub Desktop.
判断一个元素在垂直方向而言,是否在可视范围内(完全在 / 不完全在 可选)
This file contains hidden or 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
/** | |
* 原自 https://gist.github.com/simplelife7/5954021 评论区 | |
* 由于使用了 TypeScript 才有的类型注释,这些代码不能直接复制到 JS 中运行。 | |
*/ | |
/** | |
* | |
* @param {string} id 元素的 id(不包含 # 号) | |
* @param {boolean} full 选择是否要求元素全体在可视范围内。 | |
* 当 full 参数为 true 时,只有当该元素所有部分都在可视范围内,才会返回 true。 | |
* 当 full 参数为 false 时(默认),只要 viewport 内出现该元素的任何一个部分(垂直而言),就会返回 true。 | |
*/ | |
function isElementInViewport(id: string, full: boolean = false): boolean { | |
let el = document.getElementById(id); | |
let height = !full ? el.offsetHeight : 0; | |
let rect = el.getBoundingClientRect(); | |
return ( | |
rect.top >= 0 && | |
rect.left >= 0 && | |
rect.bottom <= (window.innerHeight + height || document.documentElement.clientHeight + height || window.innerHeight - height || document.documentElement.clientHeight - height) && | |
rect.right <= (window.innerWidth || document.documentElement.clientWidth) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
哇!彳亍唉