是否可以创建包含带有SASS的选择器的函数(或其他功能)?

是否可以创建包含带有SASS的选择器的函数(或其他功能)?,sass,Sass,我想能够写: div { background-size: 100%; @bgimgfunction('img1.png'); } 让SASS制作类似以下内容: div { background-size: 100%; /* Generated by the call to @bgimgfunction */ background-image:('/img/img1-medium.png'); @media (max-width: 6

我想能够写:

div {
    background-size: 100%;
    @bgimgfunction('img1.png');
}
让SASS制作类似以下内容:

div {
    background-size: 100%;
    
    /* Generated by the call to @bgimgfunction */

    background-image:('/img/img1-medium.png');
    @media (max-width: 640px) {
        background-image:('/img/img1-low.png');
    }

    @media (min-width: 1600px) {
        background-image:('/img/img1-high.png');
    }

    /* End generated by the call to @bgimgfunction */
}
mixin
我认为这不起作用,因为我无法传递参数

函数
我认为不起作用,因为它们只有在选择器之后才有效

有办法做到这一点吗?

您需要的是一个不接受参数的。鉴于图像URL的结构,我认为您需要两个参数,一个用于图像名称,另一个用于其扩展名:

@mixin bgImageFunction($imageName, $imageExt) {
    $path: '/img/' + $imageName;
    
    background-image: url("#{$path}-medium.#{$imageExt}");
    
    @media (max-width: 640px) {
        background-image: url("#{$path}-low.#{$imageExt}");
    }

    @media (min-width: 1600px) {
        background-image: url("#{$path}-high.#{$imageExt}");
    }
}

div {
    background-size: 100%;
    @include bgImageFunction('img1', 'png');
}
您还可以为扩展名使用默认参数,并仅将名称作为参数传递:

@mixin bgImageFunction($imageName, $imageExt: 'png') {
    ...
}