是的,这应该可以通过 Sass 的 @mixin 功能实现。 [Sass Documentation #mixin]
我正在使用类似的构造来构建我的类并通过例如扩展它们。过渡前缀。可以采用相同的规则/构造来构建您的“自己的”规则与变量实现。
我一直都有一个“核心”文件夹,其中包括我的 mixin 函数和变量。
在这个例子中,我向你展示了函数“vendor-prefix”和“placeholder”。对于您的解决方案,请在下面进一步查看。
我的例子
/* Vendor Prefixes */
@mixin vendor-prefix($name, $argument) {
-webkit-#{$name}: #{$argument};
-ms-#{$name}: #{$argument};
-moz-#{$name}: #{$argument};
-o-#{$name}: #{$argument};
#{$name}: #{$argument};
}
/* Placeholder */
@mixin placeholder {
&::-webkit-input-placeholder {@content}
&:-moz-placeholder {@content}
&::-moz-placeholder {@content}
&:-ms-input-placeholder {@content}
}
/* Your new Function to extend the hover, focus statements */
@mixin button-effects($color_on_hover){
&:hover, &:focus {
color: #{$color_on_hover);
}
}
To use them in a class, you can do the following.
.your_class {
display:block; width:20px; height:20px;
@include('transition', 'all .3s');
}
适合您的情况的解决方案
我稍微编辑了一下,所以该函数提供了默认颜色、悬停颜色和背景颜色的 3 个参数。我认为这在您尝试完成的大多数用例中都很有用。
// Your Mixin function for extension
// @param $color_default Default Color state of your Button
// @param $color_on_hover Color on hovering your element
// @param $background_color Background Color of your Button element (in case of you need)
@mixin btn_build($color_default, $color_on_hover, $background_color){
padding: 6px 20px;
border-radius: 2px;
color: #{$color_default};
background-color: #{$background_color};
&:hover, &:focus {
color: #{$color_on_hover};
outline: none;
}
}
// Button base class
.button {
display:inline-block;
height:34px; line-height:34px;
}
// Button white
.button.btn-white {
@include btn_build('black', 'red', 'white');
}
// Button blue
.button.btn-blue {
@include btn_build('black', 'white', 'blue');
}
编译示例代码
实际上没有压缩,让它有点可读性。
默认情况下,如果你编译你可以使用压缩。例如。使用 ruby sass 编译器我使用这个:
sass --watch source:dist --style=compressed
.button {
display: inline-block;
height: 34px;
line-height: 34px; }
.button.btn-white {
padding: 6px 20px;
border-radius: 2px;
color: black;
background-color: white; }
.button.btn-white:hover, .button.btn-white:focus {
color: red;
outline: none; }
.button.btn-blue {
padding: 6px 20px;
border-radius: 2px;
color: black;
background-color: blue; }
.button.btn-blue:hover, .button.btn-blue:focus {
color: white;
outline: none; }