1. 定义与用法
calc() 函数用于动态计算长度值
- 运算符前后都需要保留一个空格,例如:width: calc(100% - 10px);
- 任何长度值都可以使用 calc() 函数进行计算;
- calc() 函数支持 " + ", " - ", " * ", " / " 运算;
- calc() 函数使用标准的数学运算优先级规则;
2. 使用 calc 计算长度并传参
需求:
根据服务端返回的数组长度,来计算元素的宽度并在屏幕宽度变化时能够兼容,这是我们就可以考虑使用 calc 计算长度并传参。
2.1 完整代码
<template>
<div>
<div class="home">
<div class="test1" v-for="item in resArr" :key="item" :style="div1Width()"></div>
</div>
<div class="test2" :style="div2Width()"></div>
</div>
</template>
<script>
export default {
data() {
return {
resArr:[1,3,5,7] // 模拟服务端返回数据
};
},
methods: {
div1Width(){
let arrLength = this.resArr.length;
return `width: calc((100% - 200px)/${
arrLength});`
},
div2Width(){
let arrLength = this.resArr.length*100 + 'px';
return `width: calc(100% - ${
arrLength});`
},
}
};
</script>
<style lang="stylus" scoped>
.home{
display:flex;
justify-content: space-around;
.test1{
height:20px;
background-color: pink;
}
}
.test2{
margin-top:30px;
height:20px;
background-color: red;
}
</style>
2.2 效果