用django做的網(wǎng)站百度品牌
首先定義了一個(gè)名叫ScreenContainerOptions的組件,需要傳的參數(shù)如下
export type ScreenContainerOptions = {width?: string | numberheight?: string | numberscreenFit?: boolean // 是否開啟屏幕自適應(yīng),不然會(huì)按比例顯示
}
組件的主要代碼如下
onMounted(async () => {await initSize()updateSize()updateScale()window.addEventListener('resize', onResize)isReady.value = true // 執(zhí)行完上面的方法后再渲染slot插槽
})// 初始化寬高
const initSize = () => {return new Promise((resolve) => {nextTick(() => {dom = refName.valueparentDom = refNameParent.value// 獲取大屏的真實(shí)尺寸(不傳值就是dom元素的寬高)widthRef.value = props.options?.width || dom.clientWidthheightRef.value = props.options?.height || dom.clientHeight// 獲取屏幕尺寸,避免重復(fù)計(jì)算if (!screenWidthRef.value || !screenHeightRef.value) {screenWidthRef.value = window.screen.widthscreenHeightRef.value = window.screen.height}resolve(true)})})
}
// 更新寬高
const updateSize = () => {dom.style.width = `${widthRef.value || screenWidthRef.value}px`dom.style.height = `${heightRef.value || screenHeightRef.value}px`
}
// 更新縮放比例
const updateScale = () => {// window.innerWidth 獲取當(dāng)前展示區(qū)域的寬度const currentWidth = window.innerWidth// 獲取大屏最終真實(shí)的寬度const realWidth = widthRef.value || screenWidthRef.value// 是否開啟屏幕適配,不會(huì)按照比例const { screenFit } = props.options// 如果不想屏幕留白,而是自適應(yīng)寬高的話let heightScale = 1// window.innerWidth 獲取當(dāng)前展示區(qū)域的寬度const currentHeight = window.innerHeight// 獲取大屏最終真實(shí)的寬度const realHeight = heightRef.value || heightRef.valueif (screenFit) {heightScale = currentHeight / realHeight// if (parentDom) {// parentDom.style.height = dom.style.height = `${window.innerHeight}px` // 父容器寬度設(shè)置為原屏幕的寬度// }}// 算出縮放比例并賦值// 只需要根據(jù)寬度計(jì)算即可const scale = currentWidth / realWidthdom && (dom.style.transform = `scale(${scale}, ${screenFit ? heightScale : 1})`) // 不開啟screenFit的話高度不需要縮放if (parentDom) {parentDom.style.width = `${window.innerWidth}px` // 父容器寬度設(shè)置為原屏幕的寬度screenFit && (parentDom.style.height = `${window.innerHeight}px`) // 父容器寬度設(shè)置為原屏幕的寬度}
}// 瀏覽器resize事件觸發(fā)回調(diào)
const onResize = async () => {await initSize()await nextTick()updateScale()
}
組件完整代碼地址
https://github.com/jimchou-h/vue-study/blob/dev/src/components/ScreenContainer.vue