Skip to content

滚动至页面顶部

window.scrollTo() 会滚动至指定的坐标,如果设置坐标为(0,0),就会回到页面顶部

js
const goToTop = () => window.scrollTo(0, 0);
goToTop();
// Result: 将会滚动至顶部
const goToTop = () => window.scrollTo(0, 0);
goToTop();
// Result: 将会滚动至顶部

检查指定元素是否处于聚焦状态

可以使用 document.activeElement 来判断元素是否处于聚焦状态

js
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// Result: 如果处于焦点状态会返回 True 否则返回 False
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// Result: 如果处于焦点状态会返回 True 否则返回 False

滚动到顶部/底部

  • 将元素滚动到顶部最简单的方法是使用 scrollIntoView。设置 block 为 start 可以滚动到顶部;设置 behavior 为 smooth 可以开启平滑滚动。
js
const scrollToTop = (element) => element.scrollIntoView({ behavior: "smooth", block: "start" });
const scrollToTop = (element) => element.scrollIntoView({ behavior: "smooth", block: "start" });
  • *滚动到底部只需要设置 block 为 end 即可。
js
const scrollToBottom = (element) => element.scrollIntoView({ behavior: "smooth", block: "end" });
const scrollToBottom = (element) => element.scrollIntoView({ behavior: "smooth", block: "end" });

检测元素是否在屏幕中

js
const callback = (entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      // `entry.target` is the dom element
      console.log(`${entry.target.id} is visible`);
    }
  });
};

const options = {
  threshold: 1.0,
};
const observer = new IntersectionObserver(callback, options);
const btn = document.getElementById("btn");
const bottomBtn = document.getElementById("bottom-btn");
observer.observe(btn);
observer.observe(bottomBtn);
const callback = (entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      // `entry.target` is the dom element
      console.log(`${entry.target.id} is visible`);
    }
  });
};

const options = {
  threshold: 1.0,
};
const observer = new IntersectionObserver(callback, options);
const btn = document.getElementById("btn");
const bottomBtn = document.getElementById("bottom-btn");
observer.observe(btn);
observer.observe(bottomBtn);

隐藏元素

我们可以将元素的 style.visibility 设置为 hidden,隐藏元素的可见性。

缺点是元素的空间仍然会被占用。

如果设置元素的 style.display 为 none,会将元素从渲染流中删除。

js
const hideElement = (el, removeFromFlow = false) => {
  removeFromFlow ? (el.style.display = 'none')
  : (el.style.visibility = 'hidden')
}
const hideElement = (el, removeFromFlow = false) => {
  removeFromFlow ? (el.style.display = 'none')
  : (el.style.visibility = 'hidden')
}