将随机数插入到内嵌样式中以获取背景颜色

时间:2017-02-11 17:06:02

标签: javascript jquery html css

我正在尝试使用javascript或jquery输出介于0-360之间的随机数和内联样式标记,但我似乎无法弄清楚如何。任何帮助将不胜感激。

小提琴附在这里 - https://jsfiddle.net/4c59f6aw/

<div style="background-color:hsl('value to go here', 100%, 50%)"></div>

4 个答案:

答案 0 :(得分:0)

一个简单的方法是通过JavaScript添加CSS。

第一行采用随机数(最多360),第二行和第三行获取#box div并动态添加颜色。因此,每次刷新页面时,都会在框中添加不同的颜色。

background-color符号可能看起来很奇怪。它被称为模板字符串,您可以阅读更多相关信息at MDN

我不知道为什么你将jQuery标记为你的问题,因为它是一个库,需要由客户端下载。不需要达到你想要的结果。

&#13;
&#13;
var randomNumber = Math.floor(Math.random() * 360);

var myElement = document.querySelector("#box");
myElement.style.backgroundColor = `hsl(${randomNumber}, 100%, 50%)`;
&#13;
div {
  height: 200px;
  width: 200px;
}
&#13;
<div id="box"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var elements = document.querySelectorAll('.hello');

for(var i=0; i < elements.length; i++) {
  var color = Math.floor((Math.random() * 361) + 0);

  elements[i].style.background = 'hsl('+color+', 100%, 50%)';
}
div {
  height: 200px;
  width: 200px;
  margin: 10px;
  background-color:orange;
}
<div class="hello"></div>
<div class="hello"></div>
<div class="hello"></div>
<div class="hello"></div>
<div class="hello"></div>

答案 2 :(得分:0)

检查此代码snipet

  

使用Jquery

$(function(){
  $('button').click(function(){
    
     $('#change').css({'background-color': 'hsl('+randomIntFromInterval(0,255)+', 100%, 50%)'});    
  });

  function randomIntFromInterval(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}
})
div {
  height: 100px;
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="change" style="background-color:hsl(126, 100%, 50%)"></div>
<button>Change</button>

  

使用Javascript

function change(){
  var div = document.getElementById('change');
  div.style.backgroundColor = 'hsl('+randomIntFromInterval(0,255)+', 100%, 50%)';
}
function randomIntFromInterval(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}
div {
  height: 100px;
  width: 100px;
}
<div id="change" style="background-color:hsl(123, 100%, 50%)"></div>
<button onclick="change()">Change</button>

答案 3 :(得分:-2)

纯Javascript解决方案here

function populate(number, multiplier) {
  for (var i = 0; i < number; i++) {
    var div = document.createElement('div');
    div.setAttribute('style', 'background-color:hsl(' + i * multiplier +',100%,50%)');
    document.body.appendChild(div);
  }
}
populate(4, 30);