項目需求:頂部為搜索欄欄,主體內容為表格;頂部的搜索欄折疊,表格高度自適應頁面剩余的高度,且適配不同分辨率的屏幕。
1、JavaScript獲取頁面高度
- 網頁可見區域寬:document.body.clientWidth
- 網頁可見區域高:document.body.clientHeight
- 網頁可見區域寬:document.body.offsetWidth(包括邊線的寬)
- 網頁可見區域高:document.body.offsetHeight(包括邊線的寬)
- 網頁正文全文寬:document.body.scrollWidth
- 網頁正文全文高:document.body.scrollHeight
- 網頁被卷去的高:document.body.scrollTop(IE7無效)
- 網頁被卷去的左:document.body.scrollLeft(IE7無效)
- 網頁被卷去的高:document.documentElement.scrollTop(IE7有效)
- 網頁被卷去的左:document.documentElement.scrollLeft(IE7有效)
- 網頁正文部分上:window.screenTop
- 網頁正文部分左:window.screenLeft
- 屏幕分辨率的高:window.screen.height
- 屏幕分辨率的寬:window.screen.width
- 屏幕可用工作區高度:window.screen.availHeight
- 屏幕可用工作區寬度:window.screen.availWidth
- 相對於窗口左上角的X:window.event.clientX
- 相對於窗口左上角的Y:window.event.clientY
- 相對於整個頁面的X:window.event.X 相對於整個頁面的Y:window.event.Y
其中,可視區域就是不包括上下左右的工具欄、狀態欄(滾動條特殊)。
2、Vue中根據可視區域高度的自適應
項目截圖:
實際代碼:
export default { data () { return { tableMaxHeight: 100, // 表格的最大高度 } }, mounted () { window.onresize = () => { this.changeTableMaxHeight() } this.changeTableMaxHeight() }, destroyed () { window.onresize = null }, methods: { showFilterForm () { this.filterActive = !this.filterActive this.changeTableMaxHeight() }, changeTableMaxHeight () { let height = document.body.offsetHeight // 網頁可視區域高度 if (this.filterActive) { this.tableMaxHeight = height - 320 } else { this.tableMaxHeight = height - 170 } console.log(this.tableMaxHeight) } }
上述代碼通過window.onresize函數實時監聽頁面寬度和高度的改變,然后都通過document.body.offsetHeight獲取網頁可視區域高度,表格的最大高度根據可視區域的高度自動調節