JS 浏览器相关方法封装
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、退出浏览器全屏状态
和 4. 全屏显示元素 一块使用
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();
}
};
6、确定设备类型
在多设备类型的时候,需要区分不同设备显示不同的内容,样式等等。
const isMobile = () => {
return !!navigator.userAgent.match(
/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i
);
};