0
点赞
收藏
分享

微信扫一扫

关于JavaScript的技巧一

1. 滚动到页面顶部

我们可以使用 window.scrollTo() 平滑滚动到页面顶部。

const scrollToTop = () => {
  window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
};

2. 滚动到页面底部

当然,如果知道文档的高度,也可以平滑滚动到页面底部。

const scrollToBottom = () => {
  window.scrollTo({
    top: document.documentElement.offsetHeight,
    left: 0,
    behavior: "smooth",
  });
};

3. 滚动元素到可见区域

有时我们需要将元素滚动到可见区域,该怎么办? 使用scrollIntoView就足够了。

const smoothScroll = (element) => {
  element.scrollIntoView({
    behavior: "smooth",
  });
};

4.全屏显示元素

你一定遇到过这样的场景,你需要全屏播放视频并在浏览器中全屏打开页面。

const goToFullScreen = (element) => {
  element = element || document.body;
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullScreen();
  }
};

5.退出浏览器全屏状态

是的,这个和第四点一起使用,你也会出现退出浏览器全屏状态的场景。

const goExitFullscreen = () => {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  }
};

举报

相关推荐

0 条评论