Vue组件上的嵌入式CSS

时间:2019-01-21 19:40:57

标签: css vue.js

我正在尝试在vue中的div上应用背景颜色,并且能够从我的数据中传递hex_code,但是我想对背景应用rgba样式。我的语法有问题吗?

      <div
        v-for="item in itemList"
        :style="{ 'background-color': `rgba(${ item.hex_code }, 0.5)` }"
        :key="item.id">
     </div>

1 个答案:

答案 0 :(得分:3)

是的,rgba(hex, opacity)在CSS中是不允许的(但在SCSS中是可能的),必须为rgba(red, green, blue, opacity)。您想要类似的东西:

:style="{ 'background-color': `rgba(${ item.red }, ${ item.green }, ${ item.blue }, 0.5)` }"

另请参阅conversion between RGB and hex

编辑:由于您是在bound属性中执行此操作的,因此可以定义一个辅助函数,将hex_code转换为适合CSS的RGB:

:style="{ 'background-color': `rgba(${hexCodeToCSSRGB(item.hex_code)}, 0.5)` }"

具有此帮助器功能(根据链接的答案改编):

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}`
    : "0, 0, 0";
}

请注意,这会将"#ff00aa"转换为"255, 0, 170",因此在您的background-color中,您将以rgba(255, 0, 170, 0.5)结尾。

相关问题