【问题标题】:Vue - getting data attribute value in cssVue - 在css中获取数据属性值
【发布时间】:2019-07-30 23:06:12
【问题描述】:

Vue css中是否有获取数据属性值的选项?

<template>
   <p data-background="purple"> TEST </p>
</template>

<style lang="scss">
p {
  background: attr(data-background); //error
  &:after {
     background: attr(data-background); //error
  }
}
</style>

【问题讨论】:

    标签: css vue.js sass styles custom-data-attribute


    【解决方案1】:

    在这种情况下,您可以使用CSS variables

    new Vue({
      el: '#app',
      data: {
        elStyle: {
          '--background': 'lightblue',
        }
      }
    });
    p:after {
      content: 'A pseudo element';
      background: var(--background, red); // Red is the fallback value
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <p :style="elStyle"></p>
    </div>

    【讨论】:

    • 问题是我无法在 :before 和 :after 伪选择器中设置背景。
    • 如果你需要设置伪元素的样式,你可以用CSS custom properties来处理。
    • 感谢您的回答。不幸的是,我需要支持 IE11。
    猜你喜欢
    • 2017-09-16
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多