Bottom visible (底部可见即滚动至底部)
使用scrollY
,scrollHeight
和 clientHeight
来确定页面的底部是否可见。
const bottomVisible = _ =>
document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight);
// bottomVisible() -> true
Current URL (当前链接地址)
使用window.location.href
来获取当前链接地址。
const currentUrl = _ => window.location.href;
// currentUrl() -> 'https://google.com'
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;
};
// e.g. 100x100 viewport and a 10x10px element at position {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
,否则使用 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()