元素内容和背景同比缩放
-
最近做一个自适应页面,有个需求是背景和内容同比缩放(由于背景图比较特殊,如果发生偏移会很明显),所以写了一个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>
完善:
const setPosition = { mounted (el, bingding) { let { draftWidth = 1920 } = bingding.value; el.scaleRtio = window.innerWidth / draftWidth; el.setPositionFun = (scaleRtio) => { if (bingding.value.hasOwnProperty('origin')) { el.style.transformOrigin = bingding.value.origin; } else { el.style.transformOrigin = `${bingding.value.hasOwnProperty('top') ? 'top' : 'bottom'} ${(bingding.value.hasOwnProperty('left') ? 'left' : 'right')}`; } bingding.value.top && (el.style.top = `${scaleRtio * bingding.value.top}px`); bingding.value.bottom && (el.style.bottom = `${scaleRtio * bingding.value.bottom}px`); bingding.value.left && (el.style.left = `${scaleRtio * bingding.value.left}px`); bingding.value.right && (el.style.right = `${scaleRtio * bingding.value.right}px`); el.style.transform = ` scale(${scaleRtio}`; } el.setPositionFun(el.scaleRtio); el.resize = e => { el.scaleRtio = e.target.innerWidth / draftWidth; el.setPositionFun(el.scaleRtio); } window.addEventListener('resize', el.resize) }, updated (el) { el.setPositionFun(el.scaleRtio); }, unmounted (el) { window.removeEventListener('resize', el.resize); el.resize = null; el.scaleRtio = null; el.setPositionFun = null; } } export default setPosition
以弃用
-