vue + js real-time monitoring screen height DIV vertically centered goals

As always, look GIF

GIF

Code

html

BootstrapV3 front-end style to use, beginning in height when obtaining #main with $('#main').height()the results obtained have been 0, after browsing the Internet to find a solution: add to the target DIV overflow: hiddenstyle,I'm not specifically engaged in the front, not to think about why

<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

Use window.onresizelistening browser window height changes, retrieve the window height, reset #mainthe margins, that is,(当前窗口高度 - 目标DIV高度) / 2

moutedCycle code in the createdcycle are possible

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

Guess you like

Origin www.cnblogs.com/mahoshojo/p/12452910.html