从下一个数组entrie进入每个变量内部的SCSS Mixin



我想提高前端的质量标准,今天为背景图像部分构建一个小助手:

.html

<div></div>

.scss

@mixin backgroundImage($path: '/assets/images', $fileName: null, $supports: null, $fileType: '.jpg', $unitType: 'px', $startFrom: 0) {
@each $res in $supports {
@media only screen and (min-width: $startFrom / 720 / 1280 / 1920 / 2560 / Last not need) and (max-width: $res#{$unitType}) {
background-image: url("#{$path}#{$fileName}-#{$res}#{$fileType}");
}
}
}
div {
height: 100vh;
background-size: cover;
background-repeat: no-repeat;
background-position: 50%, 50%;
background-color: navajowhite;
@include backgroundImage($fileName: 'background', $supports: (720, 1280, 1920, 2560, 3840), $startFrom: 480);
}

我试着创建一个stackblitz,但后来意识到,我不能上传那里的图像。因此,如果你需要一个演示来测试,请在根目录中创建一个名为assets/images/的文件夹,并放置5个名为background-720background-1280等的文件

好的,重点是我需要:(min-width: $startFrom / 720 / 1280 / 1920 / 2560 / Last not need)在每个@each中得到最后一个@each$supports的数量。就在第一个@each中,我需要使用$startFrom

我知道这令人困惑。但我以前从未写过复杂的SCSS Mixins。我希望有人能帮我。

我认为您唯一的问题是路径之间缺少一个斜杠,因为它正在解析为/assets/imagesbackground-$sz.jpg,而且我也认为您不需要$startFrom,因为您可以将其添加到$supports数组中。

这是我把它改成的,它似乎运行得很好:

@mixin backgroundImage($path: '@/assets/images', $fileType: '.jpg', $unitType: 'px', $fileName: null, $supports: null, $startFrom: 0) {
@each $size in $supports {
@media only screen and (min-width: $startFrom#{$unitType}) and (max-width: $size#{$unitType}) {
background-image: url("#{$path}/#{$fileName}-#{$size}#{$fileType}");
}
}
}

好了,我现在明白了。。。最终工作代码:

@mixin resBgImg($path: '/assets/images/', $fileName: null, $resolutions: null, $fileType: '.jpg', $unitType: 'px', $startFrom: 0)
@for $i from 1 through length($resolutions)
$min: $startFrom
@if $i > 1
$min: nth($resolutions, $i - 1)
$max: nth($resolutions, $i)
@if $i == length($resolutions)
@media only screen and (min-width: $min + 1+$unitType)
background-image: url("#{$path}#{$fileName}-#{$max}#{$fileType}")
@else
@media only screen and (min-width: $min + if($i > 1, 1, 0)+$unitType) and (max-width: $max+$unitType)
background-image: url("#{$path}#{$fileName}-#{$max}#{$fileType}")

最新更新