-
最近做一个自适应页面,有个需求是背景和内容同比缩放(由于背景图比较特殊,如果发生偏移会很明显),所以写了一个dom内容和父级背景同比缩放的方法;
随着浏览器宽度变化,背景图也跟着缩放,内容也跟着缩放;
思路:
当前窗口宽度与设计稿宽度相除 得出 缩放比;
根据缩放比缩放元素内容;
用到定位的话,需要把 top和left值同样缩放
封装成vue(3)指令
const setPosition = { mounted(el,bingding){ let { draftWidth, top, left } = bingding.value; el.scaleRtio = window.innerWidth / draftWidth; el.setPositionFun = (scaleRtio,top,left) => { el.style.transformOrigin = `top left`; el.style.top = `${ scaleRtio * top }px`; el.style.left = `${ scaleRtio * left }px`; el.style.transform = ` scale(${ scaleRtio }`; } el.setPositionFun(el.scaleRtio, top, left); el.resize = e => { console.log(e,'e'); el.scaleRtio = e.target.innerWidth / draftWidth; el.setPositionFun(el.scaleRtio, top, left); } window.addEventListener('resize',el.resize) }, updated(){ console.log('更新'); }, unmounted(el){ window.removeEventListener('resize',el.resize); el.resize = null; el.scaleRtio = null; el.setPositionFun = null; } }
使用:
<div class="innerBox" v-setPosition="{draftWidth:1200,top:20,left:60}">dasdsa</div>
-