vue+js實時監聽屏幕高度實現目標DIV垂直居中


一如既往,先看GIF

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()
        }
    }
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM