標題重寫為:Vue中新增內聯樣式的CSS變量
P粉421119778
P粉421119778 2023-12-31 12:51:41
0
1
469

我在元件中使用 css 變量,並根據 setup() 中計算的資料設定 div 的寬度

setup(props) {
    const progressBar = PositionService.getProgressBar(props.position);
    const progressWidth = `${progressBar}%`;

    ...
    return { ..., progressWidth };
}

然後我使用這個變數作為 css 變數。

<style lang="scss" scoped>
.progress-bar-width {
  --progress-bar-width: v-bind("progressWidth");
  width: var(--progress-bar-width);
}
</style>

渲染頁面時,我注意到內聯樣式被添加到 html 父元件中,導致

<a href="#/1070/applications/status/1" class="card position-relative border-gray-300 border-hover overflow-hidden h-500px" data-v-61475b35="" style="--61475b35-progressWidth:43.0613%;">.....</a>

CSP 阻止內聯樣式,因此此方法不起作用。 如何在沒有內聯樣式的情況下使用 css 變數?

P粉421119778
P粉421119778

全部回覆(1)
P粉576184933

這是一個駭客解決方案,但由於沒有內聯樣式,這是我唯一能想到的:

為您的模板新增「樣式」元件。這將會被 DOM 中的 標籤取代。在元件內部將所需的 CSS 變數加入到 :root

<component :is="`style`">
    :root { --progress-bar-width: {{ progressWidth }}; }
</component>
<div class="progress-bar-width"></div>
<style lang="scss" scoped>
.progress-bar-width {
  width: var(--progress-bar-width);
}
</style>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!