【问题标题】:Dynamic styling on a complex selector复杂选择器上的动态样式
【发布时间】:2021-04-16 08:11:57
【问题描述】:

我在一个 vue 组件上有这个样式来改变一个引导组件;

.custom-checkbox .custom-control-input:checked ~ .custom-control-label::before {
  background-color: #f16e01;
  border-color: #707070;
}

如何使此处的背景颜色动态设置为等于数据字符串,例如colorData?在其他情况下,我会创建一个数据样式对象并使用 :style 对其进行设置,但由于这里的选择器很复杂,我认为我不能这样做。

我的应用程序中有 jquery,所以如果在我创建的钩子上以某种方式使用它并让它在渲染后以某种方式运行它也可以。

【问题讨论】:

    标签: javascript jquery css vue.js


    【解决方案1】:

    问题是,您无法访问 jquery 中的 before 元素,也无法将 data 属性添加到您的 css。但是,您可以为不同的颜色创建新的类来操作 before 元素,并在选中复选框时根据数据属性切换这些颜色。像这样:

    $(document).ready(function() {
      $('.custom-checkbox > .custom-control-input').change(function() {
        let colorClass= $(this).data('color') + '-checkbox';
        $(this).siblings('.custom-control-label').toggleClass( colorClass );
    });
    });
    .red-checkbox::before {
      background-color: red !important;
    }
    
    .green-checkbox::before {
      background-color: green !important;
    }
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input" id="customCheck1" data-color="red">
      <label class="custom-control-label" for="customCheck1">Red checkbox</label>
    </div>
    
    <div class="custom-control custom-checkbox">
      <input type="checkbox" class="custom-control-input" id="customCheck2" data-color="green">
      <label class="custom-control-label" for="customCheck2">green checkbox</label>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      相关资源
      最近更新 更多