示例圖片.png
解決問(wèn)題
- 設(shè)計(jì)稿字體大小不適用于網(wǎng)頁(yè)呈現(xiàn)
- 背景圖片雹食、視頻呈現(xiàn)偏移
- 柵格化自適應(yīng)元素偏移
- 16:9自適應(yīng)實(shí)現(xiàn)
適用范圍
HTML畜普、Javascript、Vue群叶、React吃挑、Angular
上代碼
fullContainer.js
/**
* Author: Juvos
* Email: www.704921698@qq.com
*/
class FullContainer {
allWidth = 0;
/**
* 入?yún)? * @param id 自適應(yīng)Box Id
* @param width 自適應(yīng)原始寬度钝荡,默認(rèn)1920
* @param height 自適應(yīng)原始高度,默認(rèn)1080
*/
constructor(id, width = 1920, height = 1080) {
document
.getElementById(id)
.setAttribute(
"style",
`overflow: hidden;transform-origin: left top;`
);
document.getElementById(id).style.width = `${width}px`;
document.getElementById(id).style.height = `${height}px`;
this.id = id;
this.width = width;
this.height = height;
this.allWidth = width;
this.debounce(100, this.initWH(id));
this.bindDomResizeCallback();
}
initWH(id, resize = true) {
return new Promise((resolve) => {
const dom = document.getElementById(id);
let width = dom ? dom.clientWidth : 0;
let height = dom ? dom.clientHeight : 0;
if (!dom) {
console.warn(
"DataV: Failed to get dom node, component rendering may be abnormal!"
);
} else if (!width || !height) {
console.warn(
"DataV: Component width or height is 0px, rendering abnormality may occur!"
);
}
if (resize) this.onResize();
resolve();
});
}
onResize() {
const { allWidth, id } = this;
document.getElementById(id).style.transform = `scale(${
document.body.clientWidth / allWidth
})`;
}
bindDomResizeCallback() {
window.addEventListener("resize", () => {
this.debounce(100, this.initWH(this.id));
});
}
debounce(delay, callback) {
let lastTime;
return function () {
clearTimeout(lastTime);
const [that, args] = [this, arguments];
lastTime = setTimeout(() => {
callback.apply(that, args);
}, delay);
};
}
}
使用方法
<script src="../js/fullContainer.js"></script>
<script>
new FullContainer("screenContainer");
</script>