如果是这种样式属性比较多的,用style绑定方式切换有没有简洁一些的方法呢?如handelClick3,handelClick4里的代码太多了

来源:3-12 自由编程

gsl003

2021-05-22 15:11:55

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>样式绑定</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
button{ background: purple; border:none; font-size: 20px;}
.active,.active2{ background: pink; border:2px solid yellow; font-size: 30px; }
</style>
</head>

<body>
<!--
要求:
1、页面上默认有一个按钮,按钮的样式是:背景颜色是紫色、没有边框、字体大小是20px、字体颜色是白色。
2、当点击按钮时,按钮的样式变化如下:背景颜色变为粉色、边框是2个像素的黄色边框、字体大小是30px、字体颜色变为黑色、
-->
<div id="app">
<!-- class对象绑定 -->
<button :class="{active:isActive}" @click="handelClick">class对象绑定</button>
<br /><br />
<!-- class数组绑定 -->
<button :class="[active2]" @click="handelClick2">class数组绑定</button>
<br /><br />
<!-- style对象绑定 -->
<input type="button" :style="styleObj" @click="handelClick3" value="style对象绑定">
<br /><br />
<!-- style数组绑定 -->
<input type="button" :style="[styleObj2]" @click="handelClick4" value="style数组绑定">
</div>
<script>
var vm = new Vue({
el:'#app',
data:{
isActive:false,
active2:'',
styleObj:{
background: 'purple',
border:'none',
fontSize: '20px'
},
styleObj2:{
background: 'purple',
border:'none',
fontSize: '20px'
}
},
methods:{
handelClick:function(){
this.isActive = !this.isActive;
},
handelClick2:function(){
this.active2 = this.active2 ==="active2" ? " " : "active2";
},
handelClick3:function(){
this.styleObj.background = this.styleObj.background ==="purple"?"pink":"purple";
this.styleObj.border = this.styleObj.border ==="none"?"2px solid yellow":"none";
this.styleObj.fontSize = this.styleObj.fontSize ==="20px"?"30px":"20px";
},
handelClick4:function(){
this.styleObj2.background = this.styleObj2.background ==="purple"?"pink":"purple";
this.styleObj2.border = this.styleObj2.border ==="none"?"2px solid yellow":"none";
this.styleObj2.fontSize = this.styleObj2.fontSize ==="20px"?"30px":"20px";
}
}
})
</script>
</body>

</html>


写回答

1回答

好帮手慕久久

2021-05-22

同学你好,问题解答如下:

没有很好的方式能简化代码,可以考虑直接修改this.styleObj、this.styleObj2的值:

http://img.mukewang.com/climg/60a8b19f092848ae05320509.jpg

http://img.mukewang.com/climg/60a8b1e709c649df14540550.jpg

另外,通过:style=""设置的样式是行内样式:

http://img.mukewang.com/climg/60a8b245097a6ae912410083.jpg

而处于行内的样式,优先级比较高,后期维护时不好修改,所以不鼓励将大量的样式设置在行内。因此通过:style=""设置样式时,样式并不会很多,不用担心代码太多的问题。

代码中有一处小问题:

切换过程中,文字颜色会在白色、黑色之间切换,建议添加上该功能:

http://img.mukewang.com/climg/60a8b3260905a4af06120427.jpg

http://img.mukewang.com/climg/60a8b33209c67a8d04240384.jpg

http://img.mukewang.com/climg/60a8b34609e4f17914430404.jpg

祝学习愉快!

0
hsl003
hp>好的,谢谢细心的老师,已改正

h021-05-22
共1条回复

0 学习 · 10739 问题

查看课程