Bottom visible (页面的底部是否可见)
使用 scrollY
,scrollHeight
和 clientHeight
来确定页面的底部是否可见。
- const bottomVisible = _ =>
- document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
- // bottomVisible() -> true
Element is visible in viewport (判断元素是否在可视窗口可见)
使用 Element.getBoundingClientRect()
和 window.inner(Width|Height)
值来确定给定元素是否在可视窗口中可见。 省略第二个参数来判断元素是否完全可见,或者指定 true
来判断它是否部分可见。
- const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
- const { top, left, bottom, right } = el.getBoundingClientRect();
- return partiallyVisible
- ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
- ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
- : top >= 0 && left >= 0 && bottom < = innerHeight && right <= innerWidth;
- };
- // 举个例子,有一个 100x100 可视窗口, 和一个 10x10px 元素定位在 {top: -1, left: 0, bottom: 9, right: 10}
- // elementIsVisibleInViewport(el) -> false (not fully visible)
- // elementIsVisibleInViewport(el, true) -> true (partially visible)
Get scroll position (获取滚动条位置)
如果浏览器支持 pageXOffset
和 pageYOffset
,那么请使用 pageXOffset
和 pageYOffset
,否则请使用 scrollLeft
和 scrollTop
。 你可以省略 el
参数,默认值为 window
。
- const getScrollPos = (el = window) =>
- ({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
- y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});
- // getScrollPos() -> {x: 0, y: 200}
Redirect to URL (重定向到URL)
使用 window.location.href
或 window.location.replace()
重定向到 url
。 传递第二个参数来模拟链接点击(true
– 默认值)或HTTP重定向(false
)。
- const redirect = (url, asLink = true) =>
- asLink ? window.location.href = url : window.location.replace(url);
- // redirect('https://google.com')
Scroll to top (回到顶部)
使用 document.documentElement.scrollTop
或 document.body.scrollTop
获取到顶部距离。从顶部滚动一小部分距离。使用window.requestAnimationFrame()
来实现滚动动画。
- const scrollToTop = _ => {
- const c = document.documentElement.scrollTop || document.body.scrollTop;
- if (c > 0) {
- window.requestAnimationFrame(scrollToTop);
- window.scrollTo(0, c - c / 8);
- }
- };
- // scrollToTop()