根据LESS / Javascript中的条件对常见的css规则进行分组?

问题描述 投票:0回答:1

我正在寻找一些重构帮助,以便在一个规则下对常用按钮属性进行分组,以减少CSS规则的代码量。

逻辑基本上说如果“show-footer”为真,那么我会并排显示两个按钮。否则,我会显示一个宽度为100%的按钮。我想尝试在第一条规则下对任何基本按钮属性进行分组,但不知道如何清理它。

有没有办法从两个自定义元素中抽象出逻辑,并将它们放入第一个LESS规则,使其看起来不那么脆弱?

LESS

  > .editor-properties > .editor-btn-group > button {
    display: none;
  }
}

@{customElementNamespace}search-settings.show-save {
  > .editor-properties > .editor-btn-group > .editor-save {
    display: block;
    width: 100%;
  }
}

@{customElementNamespace}search-settings.save-cancel {
  > .editor-properties > .editor-btn-group > button {
    width: 49%;
    display: inline-block;
  }
}

HTML

<div class="editor-btn-group">
  <button class="editor-cancel is-negative">
      <span class="fa fa-times"></span>
      <span>
          Cancel
      </span>
  </button>
  <button class="editor-save is-positive">
       <span class="fa fa-floppy-o">
       </span>
      <span>
          Save
      </span>
  </button>
</div>

JS

showSave: function() {
    this.$el.toggleClass('show-save', this.options.showSave === true);
},
showCancel: function() {
    this.$el.toggleClass('save-cancel', this.options.showFooter === true);
},
javascript html css less
1个回答
2
投票

我相信你可以通过flex实现这一点

您需要在按钮上使用flex-grow: 1,这样当容器上只有一个按钮和justify-content: space-between时,它们将增长到您的容器宽度,因此按钮位于let和right的边缘

div {
  display: flex;
  justify-content: space-between
}
button {
  flex-grow: 1;
}
<div class="editor-btn-group">
  <button class="editor-cancel is-negative">
      <span class="fa fa-times"></span>
      <span>
          Cancel
      </span>
  </button>
  <button class="editor-save is-positive">
       <span class="fa fa-floppy-o">
       </span>
      <span>
          Save
      </span>
  </button>
</div>

现在只有1个按钮(假装其他按钮被隐藏),请注意css是相同的

div {
  display: flex;
  justify-content: space-between
}
button {
  flex-grow: 1;
}
<div class="editor-btn-group">
  <button class="editor-cancel is-negative">
      <span class="fa fa-times"></span>
      <span>
          Cancel
      </span>
  </button>
  
</div>

用于显示您需要的按钮

.show-save .editor-cancel,
.show-cancel .editor-save { 
    display: none;
}

减少它的唯一方法是你创建一个显示none的类,并通过js添加/删除它。

© www.soinside.com 2019 - 2024. All rights reserved.