vue踩坑之路--點擊按鈕改變div樣式

有時候,咱們在作項目的時候,想經過某個按鈕來改變某個div樣式,那麼能夠經過如下代碼實現:javascript

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="vue.js"></script>
    <style type="text/css">
        .change {
            width: 500px;
            height: 500px;
            background-color: #4f77aa;
            text-align: center;
            line-height: 100px;
            font-size: 40px;
            color: white;
        }
        
        .changs {
            width: 700px;
            height: 700px;
            background-color: rgb(155, 59, 147);
            text-align: center;
            line-height: 100px;
            font-size: 40px;
            color: white;
        }
    </style>
</head>

<body>
    <div id="demo">

        <div :class="[isActive?'change':'changs']">
            經過點擊按鈕此處樣式會發生改變
        </div>
        <h1 :style="{display:activeDisplay}">
            你們好! 當按鈕被點擊時,我會和你捉迷藏哦!
        </h1>
        <button @click="changeIt">點擊改變</button>

    </div>
    <script type="text/javascript">
        new Vue({
            el: '#demo',
            data: {
                isActive: true,
                activeDisplay: 'block'
            },
            methods: {
                changeIt: function() {
                    this.isActive = !this.isActive;
                    if (this.isActive == true) {
                        this.activeDisplay = 'block';
                    } else {
                        this.activeDisplay = 'none';
                    }
                }

            }

        })
    </script>
</body>

</html>

劃重點,咱們須要給按鈕傳入一個方法,因此先要經過<button @click="changeIt">點擊改變</button>裏的@click="changeIt">來綁定該按鈕,並調用changeIt方法,此外,還須要在你想要改變樣式的div裏作綁定,即<div :class="[isActive?'change':'changs']">經過點擊按鈕此處樣式會發生改變</div>,而想要拉伸div寬度和高度,則須要用到<h1 :style="{display:activeDisplay}">你們好! 當按鈕被點擊時,我會和你捉迷藏哦!</h1>,此時,你已經作好了第一步,即綁定元素,接下來,咱們創建參數和方法,實現這一效果,先在data裏寫入兩個參數並給他們賦值isActive: true,activeDisplay: 'block';而後,咱們來寫方法:css

methods: {
                changeIt: function() {
                    this.isActive = !this.isActive;
                    if (this.isActive == true) {
                        this.activeDisplay = 'block';
                    } else {
                        this.activeDisplay = 'none';
                    }
                }

            }

而後,讓咱們來看看效果吧!html

好了,如今打開編輯器和瀏覽器快樂的嘗試吧!!!vue

相關文章
相關標籤/搜索