简体   繁体   English

从样式组中选择CSS样式

[英]Select css style from group of styles

I am generating Div for each entry in my database. 我正在为数据库中的每个条目生成Div。

<div class='db-green'>Sample Code</div>
<div class='db-blue'>Sample Code</div>
<div class='db-blue'>Sample Code</div>
<div class='db-yellow'>Sample Code</div>

What I desire is to select the color in Div class by random supose by defining the color's inside an array. 我想要的是通过在数组中定义颜色来通过随机调整在Div类中选择颜色。

I am hoping for a solution with Less or sass or should i use JS ? 我希望使用Less或sass解决方案,还是应该使用JS?

There is a solution to a problem similar to the one you called out: randomly display a div class using JQuery 有一个类似于您所提到的问题的解决方案: 使用JQuery随机显示div类

You can use jQuery to define color to random div elements: 您可以使用jQuery为随机div元素定义颜色:

var divs = ['.db-green', '.db-blue', '.db-yellow']; // possible divs
var color = ["blue", "yellow", "red"]; // potential colors
var random = Math.floor(Math.random() * divs.length);
var entry = divs[random];
$(entry).css("color", color[0]);

You can use a JavaScript function that generates a random color: 您可以使用生成随机颜色的JavaScript函数:

function getColor() {
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);

    return "#"+ r.toString(16) + g.toString(16) + b.toString(16) ;
}

And then use JS DOM (or JQuery) to change the CSS background-color attribute of each div : 然后使用JS DOM(或JQuery)更改每个div的CSS background-color属性:

var divs = document.getElementsByTagName("div");

for(var i = 0; i < divs.length; i++) {
    divs.item(i).style.backgroundColor = getColor();
    divs.item(i).innerHTML = getColor();
}

See JSFiddle 参见JSFiddle

UPDATE : You can also call a method like that inside Less using backticks to have access to the underlying JavaScript processor (I'm not sure if this will work in the non-JavaScript Less implementations such as less4j, since it's not a documented feature). 更新 :您还可以使用反引号在Less内调用类似方法,以访问底层的JavaScript处理器(我不确定这是否可以在非JavaScript Less实施中使用,例如less4j,因为它不是文档功能) 。 This mixin: 这个mixin:

.generateColor() { 
    @color: color(`"#" + (Math.random()*0xFFFFFF<<0).toString(16)`);
}

will set the @color variable to a randomly generated color. 会将@color变量设置为随机生成的颜色。 You can then use it in a selector block: 然后可以在选择器块中使用它:

.db-color-1 {
    .generateColor();
    background-color: @color;
}

.db-color-2 {
    .generateColor();
    background-color: @color;
}

.db-color-3 {
    .generateColor();
    background-color: @color;
}

And each class will have (hopefully) a different color. 每个类将(希望)具有不同的颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM