有时候,我们在做项目的时候,想通过某个按钮来改变某个div样式,那么可以通过以下代码实现:
<!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 {
500px;
height: 500px;
background-color: #4f77aa;
text-align: center;
line-height: 100px;
font-size: 40px;
color: white;
}
.changs {
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'
;然后,我们来写方法:
methods: {
changeIt: function() {
this.isActive = !this.isActive;
if (this.isActive == true) {
this.activeDisplay = 'block';
} else {
this.activeDisplay = 'none';
}
}
}
然后,让我们来看看效果吧!
好了,现在打开编辑器和浏览器快乐的尝试吧!!!