vue+js实时监听屏幕高度实现目标DIV垂直居中
一如既往,先看GIF
代码
html
前端样式使用的BootstrapV3,最开始在获取#main的高度的时候用$('#main').height()
得到的结果一直为0,网上浏览后找到了解决方案:给目标DIV加上overflow: hidden
的样式,我不是专门搞前端的,不去想为什么了
<div id="main" style="overflow: hidden" :style="mainStyle">
<div class="col-sm-4 col-sm-offset-4">
<div class="form-group">
<img src="/img/lalafaye-vector.png" style="width: 100%">
</div>
</div>
<div class="col-sm-2 col-sm-offset-5">
<div class="form-group">
<input v-model="password" name="password" type="password" class="form-control" placeholder="password">
</div>
<div class="form-group">
<button @click="login()" class="btn btn-success" style="width: 100%">LOG IN</button>
</div>
</div>
</div>
js
利用window.onresize
监听浏览器窗口高度变化,重新获取窗口高度,重置#main
的上外边距,即(当前窗口高度 - 目标DIV高度) / 2
mouted
周期里的代码放在created
周期里也是可以的
var vue = new Vue({
el: '#app',
data: {
password: '',
mainStyle: {
marginTop: ''
},
mainHeight: $('#main').height()
},
methods: {
login: function () {
axios
.post(
'/login',
Qs.stringify({username: 'admin', password: this.password})
)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error);
});
},
setMainMarginTop: function () {
let currentScreenHeight = $(window).height() || $(document).height();
this.mainStyle.marginTop = (currentScreenHeight - this.mainHeight) / 2 + 'px';
}
},
watch: {
},
created: function () {
this.setMainMarginTop()
},
mounted: function () {
window.onresize = () => {
this.setMainMarginTop()
}
}
});