css - 捕获并使用 SASS 文件中的所有图像 URL,以使用仅 css 预加载

标签 css regex sass

我最近开始为一个元素使用背景图像的纯 css 图像预加载。

//preload images
body:after{  
    display: none;
    content: url(img01.png) url(img02.png);
}

//use images
li.one { background-image: (img01.png) }
li.two { background-image: (img02.png) }

我从 SCSS 制作我的 CSS 文件,想知道是否有某种方法可以使用 SASS 来运行文件并创建主体:从整个文件的背景图像 URL 预加载之后?

如果没有,您最好的解决方案是什么,在编译 CSS 文件后制作一个脚本以使用 Regex 执行此步骤?

最佳答案

@yorbro 解决方案适用于这种特定情况,但我认为最好只使用一个函数同时执行这两件事,将图像路径添加到 $preload-images 列表并返回值。这是 preload-img() 函数:

// This declare a list variable to store all images to preload
$preloaded-images: ();

// This function will append the image or images to $preload-images and returns img path values
@function preload-img($img-path) {
    $output: ();
    @each $img in $img-path {
        $preloaded-images: append($preloaded-images, url($img));
        $output: append($output, url($img), comma);
    }
    @return $output;
}

使用此功能,您可以使用背景或背景图像属性,并且可以传递多个图像路径来创建多个背景。正如@yorbro 所说,您应该在整个 CSS 的末尾添加 body:after:

// Use images, you can use background or background-image
// Note that you can pass a list of paths to preload-image function
li.one { background: preload-img("img01.png" "img02.png"); }
li.two { background-image: preload-img("img02.png"); }

//preload images
body:after{
    display: none;
    content: $preloaded-images;
}

关于css - 捕获并使用 SASS 文件中的所有图像 URL,以使用仅 css 预加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18781138/

相关文章:

css - 将 'body'字体应用到 'p'(段落)的所有浏览器,Internet Explorer除外

正则表达式查找括号和文本

java - 正则表达式删除任何 ipv6 地址的前导零

laravel - 如何在 Laravel 5 中将 CSS 文件添加到 app.css?

html - 消除两个 svg 元素之间的间隙

javascript - 显示一个 <input type ="checkbox"> 元素,中间有一个框而不是复选标记

html - 进度条 CSS 样式问题

c++ - 用于提取括号内所有内容的正则表达式

css - Bourbon neat 在我的移动优先设置中表现不佳

typescript - Material UI按钮删除焦点框架