我正在寻找一些重构帮助,以将常用按钮属性分组在一个规则下,以减少我的 CSS 规则的代码量。
逻辑基本上是说,如果“show-footer”为真,那么我会并排显示两个按钮。否则,我会显示一个 100% 宽度的按钮。我想尝试根据第一条规则对任何基本按钮属性进行分组,但不确定如何清理它。
有没有办法从两个自定义元素中抽象出该逻辑并将它们放入第一个 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);
},
最佳答案
我相信你可以用 flex 实现这一点
您需要在按钮上使用 flex-grow: 1
以便当只有 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>
现在只有一个按钮(假装另一个按钮被隐藏),注意 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;
}
减少它的唯一方法是创建一个不显示的类并通过 js 添加/删除它。
关于javascript - 根据 LESS/Javascript 中的条件对常见的 css 规则进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49115189/