一个SCSS里mixin的使用例子
发布日期:2021-06-30 14:44:16
浏览次数:2
分类:技术文章
本文共 1695 字,大约阅读时间需要 5 分钟。
Mixins are the Sass equivalent of macros in other programming languages. If you’ve programmed before you could think of them as functions, procedures, or methods, but they aren’t technically any of these concepts because their function is to generate code at compile time not execute code at run time.
可以把mixins当成编程语言里的宏,但是技术上说,scss mixins用于在编译器生成代码,而不是在运行时执行代码。
一个例子:
a.button { background: black; color: white; padding: 10px 20px; @include border-radius(5px);}
编译之后:
a.button { background: black; color: white; padding: 10px 20px; -moz-border-radius: 5px; -webkit-border-radius: 5px; -ms-border-radius: 5px; -o-border-radius: 5px; -khtml-border-radius: 5px; border-radius: 5px;}
I used the @include directive to tell Sass that I wanted to call out to a mixin.
使用@include指令,告诉sass,需要在css里call out mixin. 通过括号传递参数。
看下border-radius的实现代码:
@mixin border-radius($radius) { -moz-border-radius: $radius; -webkit-border-radius: $radius; -ms-border-radius: $radius; border-radius: $radius;}
一个mixin传递默认参数的做法:
@mixin border-radius($radius: 5px) { ...}
或者定义一个全局变量:
$default-border-radius: 5px !default;@mixin border-radius($radius: $default-border-radius) { ...}
scss mixin里还支持条件指令@if:
@mixin border-radius($radius: 5px, $moz: true, $webkit: true, $ms: true) { @if $moz { -moz-border-radius: $radius; } @if $webkit { -webkit-border-radius: $radius; } @if $ms { -ms-border-radius: $radius; } border-radius: $radius;}
上面的用法叫做keyword argument.
这样,如果项目里我们不考虑对IE的支持,只需要下面这样写就行了:
@include border-radius($ms: false);
而不用这种繁琐的写法:
@include border-radius(5px, true, true, true);
也不需要按照顺序传递参数:
@include border-radius($ms: false, $radius: 10px);
转载地址:https://jerry.blog.csdn.net/article/details/114035373 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
不错!
[***.144.177.141]2024年05月05日 11时37分45秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Python 编码错误的本质原因
2019-05-01
Python 开发者都会遇到的错误:UnboundLocalError
2019-05-01
用 Python 送“爱心”
2019-05-01
理解HTTPS为什么安全前,先看看这些东西
2019-05-01
代码这样写不止于优雅(Python版)
2019-05-01
只有1%的程序员搞懂过浮点数陷阱
2019-05-01
Erlang 之父 Joe Armstrong 去世
2019-05-01
一名 Google 工程师的大数据处理经验
2019-05-01
30分钟学会pyecharts数据可视化
2019-05-01
从一个骗子身上学到的
2019-05-01
关于Python爬虫,这里有一条高效的学习路径
2019-05-01
Python学习指南,看这篇清晰多了!
2019-05-01
命名难,难于上青天
2019-05-01
记一件小事
2019-05-01
史上最烂项目:苦撑12年,600多万行代码...
2019-05-01
斯坦福后空翻机器人设计、代码全开源,成本降至3000美元,人人皆可DIY
2019-05-01
请停止学习框架
2019-05-01
考研比惨五大专业排行榜,第一名没人不服!
2019-05-01
没钱没公司,怎么做一款付费产品
2019-05-01
Python 3.8 新特性来袭
2019-05-01