問題描述:
做的大屏,設計稿事1920*1080 的,但是在不同分辨率的電腦上,顯示不同,有得太大有的太小
解決思路:
給最外面的盒子做縮放,動態獲取計算的屏幕的大小,然后寬高分別與1920和1080做百分比,然后進行比例縮放
代碼:
/** * 入參 * @param id 自適應Box Id * @param width 自適應原始寬度,默認1920 * @param height 自適應原始高度,默認1080 */ FullContainer(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 },${document.body.clientHeight / this.height})`; }, 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); }; },
注: 這也是借鑒的網友的,但是博客地址找不到了,侵權請聯系