基于现有类的Sass'if'语句 [英] Sass 'if' statement based on existing class
问题描述
我是Sass的新手,并且想使用'if'语句来检测元素上的现有类以生成相关的CSS.
I'm new to Sass and would like to use the 'if' statement to detect an existing class on an element in order to generate the relevant css.
我的设置中包含大量Javascript生成的图像,这些图像被分配了唯一的ID,以及一类图片"和一个随机分配的上,右,下或左类.
My setup has a large number of Javascript generated images, which are assigned a unique ID, as well as a class of "picture" and a randomly assigned class of either top, right, bottom or left.
我还在Sass上使用随机函数(在这里找到: https://gist.github.com /chriseppstein/1561650 ),并希望为每个ID分配不同的值,以便将每个元素随机放置.
I am also using a random function for Sass (found here: https://gist.github.com/chriseppstein/1561650), and would like a different value assigned to each ID, so that each element is randomly positioned.
我的SCSS具有以下内容,它们根据分配给它的类来定位图像:
My SCSS has the following, which positions the images based on which class it was assigned:
@for $i from 0 through $number-of-pictures {
#picture-#{$i}{
&.top {
left: random($stage-width);
}
&.right {
top: random($stage-height);
}
&.bottom {
left: random($stage-width);
}
&.left {
top: random($stage-height);
}
}
}
这很好用,但是会创建大量未使用的声明块.例如,#picture-38被分配了类".top",因此我只需要第一个声明块,但是CSS会导出所有选项:
This works well, but creates a ton of unused declaration blocks. For example, #picture-38 was assigned the class ".top", so all I need is the first declaration block, but the CSS exports all the options:
#picture-38.top {
left: 38px; //This is a random number that is different for each ID.
}
#picture-38.right {
top: 28px;
}
#picture-38.bottom {
left: 12px;
}
#picture-38.left {
top: 47px;
}
我需要的是if语句,该语句在解析CSS之前检测元素是否具有类.像这样:
What I need is an if statement, that detects if the element has a class before parsing the css. Something like:
@if "#picture-#{$i} has class $class-top" {
&.top {
left: random($stage-width);
}
}
有什么想法吗?
推荐答案
答案是,您无法使用SASS/SCSS做到这一点.
您正在尝试检测类对DOM元素的拥有/分配.
You are trying to detect the possession/assignment of a class to a DOM element.
与DOM元素进行交互的方式是JavaScript
The way to interact with DOM elements is JavaScript
您需要做的是使用JavaScript检测"picture-x#"是否具有"class-top"类,然后相应地设置随机的top
值.
What you need to do is use JavaScript to detect if "picture-x#" has class "class-top" and then set a random top
value accordingly.
例如
var picture = document.GetElementById('picture-1');
var pic_class = picture.className
if(pic_class.indexOf('class-top') != -1)
{
/*Returns a random number between 1 and 100*/
picture.style.top = Math.floor((Math.random()*100)+1) + 'px';
}
旁注:top
需要一个测量单位(例如px
),因此+ 'px'
Sidenote: top
requires a unit of measurement (e.g. px
), hence the + 'px'
这篇关于基于现有类的Sass'if'语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!