超实用的 JavaScript 浏览器代码片段

Bottom visible (页面的底部是否可见)

使用 scrollYscrollHeight 和 clientHeight 来确定页面的底部是否可见。

  1. const bottomVisible = _ =>
  2. document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
  3. // bottomVisible() -> true


Element is visible in viewport (判断元素是否在可视窗口可见)

使用 Element.getBoundingClientRect() 和 window.inner(Width|Height) 值来确定给定元素是否在可视窗口中可见。 省略第二个参数来判断元素是否完全可见,或者指定 true 来判断它是否部分可见。

  1. const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
  2. const { top, left, bottom, right } = el.getBoundingClientRect();
  3. return partiallyVisible
  4. ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
  5. ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
  6. : top >= 0 && left >= 0 && bottom < = innerHeight && right <= innerWidth;
  7. };
  8. // 举个例子,有一个 100x100 可视窗口, 和一个 10x10px 元素定位在 {top: -1, left: 0, bottom: 9, right: 10}
  9. // elementIsVisibleInViewport(el) -> false (not fully visible)
  10. // elementIsVisibleInViewport(el, true) -> true (partially visible)


Get scroll position (获取滚动条位置)

如果浏览器支持 pageXOffset 和 pageYOffset ,那么请使用 pageXOffset 和 pageYOffset ,否则请使用 scrollLeft 和 scrollTop 。 你可以省略 el 参数,默认值为 window

  1. const getScrollPos = (el = window) =>
  2. ({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
  3. y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});
  4. // getScrollPos() -> {x: 0, y: 200}


Redirect to URL (重定向到URL)

使用 window.location.href 或 window.location.replace() 重定向到 url 。 传递第二个参数来模拟链接点击(true – 默认值)或HTTP重定向(false)。

扫描二维码关注公众号,回复: 2290924 查看本文章
  1. const redirect = (url, asLink = true) =>
  2. asLink ? window.location.href = url : window.location.replace(url);
  3. // redirect('https://google.com')


Scroll to top (回到顶部)

使用 document.documentElement.scrollTop 或 document.body.scrollTop 获取到顶部距离。从顶部滚动一小部分距离。使用window.requestAnimationFrame() 来实现滚动动画。

  1. const scrollToTop = _ => {
  2. const c = document.documentElement.scrollTop || document.body.scrollTop;
  3. if (c > 0) {
  4. window.requestAnimationFrame(scrollToTop);
  5. window.scrollTo(0, c - c / 8);
  6. }
  7. };
  8. // scrollToTop()



猜你喜欢

转载自blog.csdn.net/qq_26522773/article/details/79298311