[英]Shorten repetitive CSS
I'm wondering if there is a way to shorten repetitive css code which only different by the given url.我想知道是否有一种方法可以缩短重复的 css 代码,它只因给定的 url 而不同。
the class is always named .bg-login-[n]
and the url represents the same number.该类始终命名为
.bg-login-[n]
并且 url 代表相同的数字。
The solution I'm consindering is to somehow combine CSS and JS to loop through an array of filenames.我正在考虑的解决方案是以某种方式结合 CSS 和 JS 来遍历文件名数组。 is there a simpler or "cleaner" way?
有没有更简单或“更清洁”的方法?
for example:例如:
.bg-login-1{
background: url(/images/login/login-1.jpg) no-repeat center center;
}
.bg-login-2{
background: url(/images/login/login-2.jpg) no-repeat center center;
}
.bg-login-3{
background: url(/images/login/login-3.jpg) no-repeat center center;
}
.bg-login-4{
background: url(/images/login/login-4.jpg) no-repeat center center;
}
.bg-login-5{
background: url(/images/login/login-5.jpg) no-repeat center center;
}
No JS needed.不需要 JS。 Just repeat numbers or use SCSS for loop.
只需重复数字或使用 SCSS 循环。
.bg {
background-position: center center;
background-repeat: no-repeat:
}
.bg-1 {
background-image: url(/images/login/login-1.jpg);
}
.bg-2 {
background-image: url(/images/login/login-2.jpg);
}
/* ... */
/* SCSS */
@for $i from 1 through N {
.bg-#{$i} {
background-image: url(/images/login/login-#{$i}.jpg);
}
}
.bg-login-1 {
background-image: url(/images/login/login-1.jpg);
}
.bg-login-2 {
background-image: url(/images/login/login-2.jpg);
}
.bg-login-3 {
background-image: url(/images/login/login-3.jpg);
}
.bg-login-4 {
background-image: url(/images/login/login-4.jpg);
}
.bg-login-5 {
background-image: url(/images/login/login-5.jpg);
}
And for the last three properties, do this:对于最后三个属性,请执行以下操作:
.bg-login-1,
.bg-login-2,
.bg-login-3,
.bg-login-4,
.bg-login-5 {
background-repeat: no-repeat;
background-position: center;
}
or do this:或这样做:
.bg-login {
background-repeat: no-repeat;
background-position: center;
}
Add classname bg-login
to all the button.将类
bg-login
添加到所有按钮。
<script>
const btns = document.getElementsByClassName('bg-login'); //get all the buttons
const i=1;
for(const btn in btns){
btn.style.backgroundImage = `url(/images/login/login-${i}.jpg) no-repeat center center`;
i++;
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.