超実用的なJavaScriptブラウザコードクリップ


Bottom visible(ページの下部に表示されるかどうか)
使用  scrollY , scrollHeight  および  clientHeight  をクリックして、テストする%PRODUCTNAMEドキュメントを選択してから、
const bottomVisible = _ =>
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
//bottomVisible() -> true
Elementis visible in viewport(要素が表示されるかどうかを判断する)
使用  Element.getBoundingClientRect()  および  window.inner(Width|Height)  値を使用して、指定した要素が表示されるかどうかを決定します.2番目のパラメータを省略して要素が完全に表示されているかどうかを判断したり、指定したりします.  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;
};
//例を挙げると、100 x 100のビジュアルウィンドウと、10 x 10 px要素が{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  . 2番目のパラメータを渡してリンククリックをシミュレートします(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()