移动端横竖屏适配
监听屏幕转动
屏幕转动,设置根元素字号。
win.addEventListener("orientationchange", setFont, false);
获取横竖屏状态
var orientation = window.orientation;
if (orientation === 180 || orientation === 0 ) {
console.log("竖屏");
}
if (orientation === 90 || orientation === -90 ) {
console.log("横屏");
}
根据横竖屏设置设计稿大小
var k = 0;
// 竖屏
if (orientation === 180 || orientation === 0) {
k = 750;
console.log("竖屏")
}
// 横屏
if (orientation === 90 || orientation === -90) {
k = 1624;
console.log("横屏")
}
设置根元素字号
function setFont() {
var html = document.documentElement;
var orientation = win.orientation;
var k = 0;
// 竖屏
if (orientation === 180 || orientation === 0) {
k = 750;
console.log("竖屏")
}
// 横屏
if (orientation === 90 || orientation === -90) {
k = 1624;
console.log("横屏")
}
html.style.fontSize = (html.clientWidth / k) * 100 + "px";
}
整体代码
//屏幕适应
(function (win, doc) {
if (!win.addEventListener) return;
var html = document.documentElement;
function setFont() {
var html = document.documentElement;
var orientation = win.orientation;
var k = 0;
// 竖屏
if (orientation === 180 || orientation === 0) {
k = 750;
console.log("竖屏")
}
// 横屏
if (orientation === 90 || orientation === -90) {
k = 1624;
console.log("横屏")
}
html.style.fontSize = (html.clientWidth / k) * 100 + "px";
}
setFont();
// setTimeout(function () {
// setFont();
// }, 300);
// doc.addEventListener("DOMContentLoaded", setFont, false);
win.addEventListener("orientationchange", setFont, false);
win.addEventListener("resize", setFont, false);
// win.addEventListener("load", setFont, false);
})(window, document);