Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

Is it possible to create functions (or something else) that include selectors with SASS?

I want to be able to write:

div {
    background-size: 100%;
    @bgimgfunction('img1.png');
}

and have SASS produce something like:

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 */
}

mixins I think don't work because I can't pass a parameter

functions I think don't work because they are only valid after a selector.

Is there a way to do this?

question from:https://stackoverflow.com/questions/65847764/is-it-possible-to-create-functions-or-something-else-that-include-selectors-wi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you need is a @mixin which does take parameters. Given the structure of your image URLs, I think you need two arguments, one for the image name and one for its extension:

@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');
}

You can also use a default parameter for the extension and only pass the name as argument:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...