遇到需求,登錄頁面需要頂部和底部上下等高,並且隨着瀏覽器自適應上下高度。
解決方法:
vue界面的data中先定義
data() { return { windowHeight: "", topHeight: "" }; },
mounted中:
mounted() { this.windowHeight = window.innerHeight; // 瀏覽器可見區域高度 this.topHeight = (this.windowHeight - 600) / 2 + "px"; // 瀏覽器可見區域高度 - 600為背景圖高度 / 2 = 平均上下高度 window.onresize = () => { return (() => { this.windowHeight = window.innerHeight; this.topHeight = (this.windowHeight - 600) / 2 + "px"; })(); }; }
mouted為界面加載時執行的方法,那么,應該怎么監聽到mouned中的 window.onresize呢?
// 使用vue的watch事件監聽 watch: { topHeight(val) { this.topHeight = val; } },
再在頂部元素中綁定style即可。
<div :style="{height:topHeight}"> <span>xx管理平台</span> </div>
最后~再延伸一下:頂部一般是有logo或者文字,該怎樣讓頂部的內容也自適應垂直居中呢?
最簡單的方法,在頂部的外層加上樣式 display:flex;其里面的內容,加上margin:auto; 即可實現上下垂直居中。
