const forceLandscape = ((id = '#hitmouse') => {
const handler = () => {
let width = document.documentElement.clientWidth;
let height = document.documentElement.clientHeight;
let targetDom = document.querySelector(id);
if (!targetDom) return;
// 如果宽度比高度大,则认为处于横屏状态
// 也可以获取 window.orientation 方向来判断屏幕状态
if (width > height) {
targetDom.style.position = 'absolute';
targetDom.style.width = `${width}px`;
targetDom.style.height = `${height}px`;
targetDom.style.left = `${0}px`;
targetDom.style.top = `${0}px`;
targetDom.style.transform = 'none';
targetDom.style.transformOrigin = '50% 50%';
} else {
targetDom.style.position = 'absolute';
targetDom.style.width = `${height}px`;
targetDom.style.height = `${width}px`;
targetDom.style.left = `${0 - (height - width) / 2}px`;
targetDom.style.top = `${(height - width) / 2}px`;
targetDom.style.transform = 'rotate(90deg)';
targetDom.style.transformOrigin = '50% 50%';
}
};
const handleResize = () => {
setTimeout(() => {
handler();
}, 300);
};
window.addEventListener('resize', handleResize);
handler();
})();
移动端h5强制横屏的方法
最新推荐文章于 2024-09-06 17:11:11 发布
文章介绍了如何使用JavaScript实现一个名为constforceLandscape的函数,根据设备的宽高比和屏幕方向自动调整目标DOM元素的样式,包括位置、大小和旋转,以适应横竖屏显示。
摘要由CSDN通过智能技术生成