vue使用CSS變量詳解
vue使用CSS 變量
首先,我們要先知道什么是CSS變量
在我們知道什么是CSS變量之后,我們嘗試把它在項目中運用起來,一些需要動態(tài)計算的值,我們就可以使用它快速的實現(xiàn)效果。
示例一
其中keyframes是不能直接在html中書寫的,那么如何不使用js就能根據(jù)傳入的值達到對應(yīng)的效果呢?
如下:
<template>
<div
:style="{ '--deviation': '-' + deviation }"
class="text"
>
{{ text }}
</div>
</template>
<script>
export default {
name: 'QTest',
props: {
text: {
type: String,
default: '請傳入內(nèi)容'
},
// 動態(tài)傳入不同的值,根據(jù)不同的值得出最終的樣式
deviation: {
type: String,
default: '75%'
}
},
}
</script>
<style lang="scss" scoped>
.text {
width: 100px;
overflow: hidden;
transition-delay: 5s;
animation: itemSlide 5s linear infinite;
}
@keyframes itemSlide {
0% {
transform: translateX(0%);
}
100% {
/*使用變量*/
transform: translateX(var(--deviation));
}
}
</style>
示例二
有的時候,一些屬性我們可能需要根據(jù)一些條件計算得來,那么也能很好的去使用它。
如下:
<template>
<div
:style="{ '--lineheight': lineheight }"
class="text"
>
<div class="container"></div>
</div>
</template>
<script>
export default {
name: 'QTest',
props: {
lineheight: {
type: String,
default: '200px'
}
},
}
</script>
<style lang="scss" scoped>
.text {
width: 100px;
height: 400px;
overflow: hidden;
.container {
height: calc(100% - var(--lineheight));
background-color: red;
}
}
</style>
就得到一個高度為200px的盒子:

補充:
獲取元素樣式:getComputedStyle([el])
const styles = getComputedStyle(document.documentElement)
const value = String(styles.getPropertyValue('--lineheight')).trim()
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
在Vue 中實現(xiàn)循環(huán)渲染多個相同echarts圖表
這篇文章主要介紹了在Vue 中實現(xiàn)循環(huán)渲染多個相同echarts圖表,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
Vue Element前端應(yīng)用開發(fā)之開發(fā)環(huán)境的準(zhǔn)備工作
這篇文章主要介紹了Vue Element前端應(yīng)用開發(fā)之開發(fā)環(huán)境的準(zhǔn)備工作,對Vue感興趣的同學(xué),可以來學(xué)習(xí)一下2021-05-05
Vue3.4中v-model雙向數(shù)據(jù)綁定新玩法詳解
defineModel?是一個新的?<script?setup>?宏,旨在簡化支持?v-model?的組件的實現(xiàn),?這個宏用來聲明一個雙向綁定?prop,下面我們就來看看他的具體使用吧2024-03-03

