vue項目如何監聽窗口變化,達到頁面自適應?

【自適應】向來是前端工程師須要解決的一大問題——即使做爲當今很是火熱的vue框架,也沒法擺脫——雖然elementui、iview等開源UI組件庫層出不窮,但官方庫畢竟不可能知足所有需求,所以咱們能夠經過【監聽窗口變化】達到想要的絕大部分自適應效果。css

獲取窗口寬度:document.body.clientWidth
監聽窗口變化:window.onresize前端

同時回顧一下JS裏這些方法:
網頁可見區域寬:document.body.clientWidth
網頁可見區域高:document.body.clientHeight
網頁可見區域寬:document.body.offsetWidth (包括邊線的寬)
網頁可見區域高:document.body.offsetHeight (包括邊線的寬)vue

咱們將document.body.clientWidth賦值給data中自定義的變量:前端工程師

data:{框架

screenWidth: document.body.clientWidth

}iview

在頁面mounted時,掛載window.onresize方法:函數

mounted () {ui

const that = this
window.onresize = () => {
    return (() => {
        window.screenWidth = document.body.clientWidth
        that.screenWidth = window.screenWidth
    })()
}

}this

監聽screenWidth屬性值的變化,打印並觀察screenWidth發生變化的值:spa

watch:{

screenWidth(val){
    // 爲了不頻繁觸發resize函數致使頁面卡頓,使用定時器
    if(!this.timer){
        // 一旦監聽到的screenWidth值改變,就將其從新賦給data裏的screenWidth
        this.screenWidth = val
        this.timer = true
        let that = this
        setTimeout(function(){
            // 打印screenWidth變化的值
            console.log(that.screenWidth)
            that.timer = false
        },400)
    }
}

}

好!既然能夠監聽到窗口screenWidth值的變化,就能夠根據這個值設定不一樣的自適應方案了!

【舉個例子:div或img圖片高度隨寬度自適應】

div或img的寬度自適應很簡單——設定css裏width屬性爲百分比便可——可是高度呢?父級元素的高度並非固定的(一般都是子級元素撐開的)

圖片描述

如上圖,一個相似【圖片庫】的功能,當屏幕放大縮小時,咱們能夠設置外層邊框(也就是灰色框框)的寬度爲100%,以達到自適應——但高度沒法設置,所以咱們須要:
1.數據加載完後,獲取圖片(或外層框)的寬度
2.根據這個寬度,設置外層框的高度(如:寬度的60%)
3.監聽窗口screenWidth值的變化,每次變化都從新獲取寬度,並從新設置高度

因此,咱們只需在前文代碼的基礎上,添加如下代碼,以確保屏幕縮放時,每次監聽寬度變化:

mounted() {

// 一、數據首次加載完後 → 獲取圖片(或外層框)寬度,並設置其高度
this.$nextTick(() => {
    // 獲取圖片(或外層框)
    let imgBox = this.$refs.imgBox
    // 獲取其寬度
    let wImgbox = imgBox[0].getBoundingClientRect().width
    // 設置其高度(以寬度的60%爲例)
    this.imgBox.height = 0.6 * wImgbox + 'px'
})
// 二、掛載 reisze 事件 → 屏幕縮放時監聽寬度變化
const that = this
window.onresize = () => {
    return (() => {
        // window.screenWidth = document.body.clientWidth
        // that.screenWidth = window.screenWidth
        // console.log(that.screenWidth)
        this.$nextTick(() => {
            let imgBox = this.$refs.imgBox
            let wImgbox = imgBox[0].getBoundingClientRect().width
            this.imgBox.height = 0.6 * wImgbox + 'px'
        })
    })()
}

},

最終實現效果以下:

圖片描述

相關文章
相關標籤/搜索