【自適應】向來是前端工程師需要解決的一大問題——即便作為當今非常火熱的vue框架,也無法擺脫——雖然elementui、iview等開源UI組件庫層出不窮,但官方庫畢竟不可能滿足全部需求,因此我們可以通過【監聽窗口變化】達到想要的絕大部分自適應效果。
獲取窗口寬度:document.body.clientWidth
監聽窗口變化:window.onresize
同時回顧一下JS里這些方法:
網頁可見區域寬:document.body.clientWidth
網頁可見區域高:document.body.clientHeight
網頁可見區域寬:document.body.offsetWidth (包括邊線的寬)
網頁可見區域高:document.body.offsetHeight (包括邊線的寬)
我們將document.body.clientWidth賦值給data中自定義的變量:
data:{ screenWidth: document.body.clientWidth }
在頁面mounted時,掛載window.onresize方法:
mounted () { const that = this window.onresize = () => { return (() => { window.screenWidth = document.body.clientWidth that.screenWidth = window.screenWidth })() } }
監聽screenWidth屬性值的變化,打印並觀察screenWidth發生變化的值:
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() { // 1、數據首次加載完后 → 獲取圖片(或外層框)寬度,並設置其高度 this.$nextTick(() => { // 獲取圖片(或外層框) let imgBox = this.$refs.imgBox // 獲取其寬度 let wImgbox = imgBox[0].getBoundingClientRect().width // 設置其高度(以寬度的60%為例) this.imgBox.height = 0.6 * wImgbox + 'px' }) // 2、掛載 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' }) })() } },
最終實現效果如下:
文章來源:https://segmentfault.com/a/1190000016512967