Выбор рандомного элемента из массива для элемента
Есть 3 дива.
Есть массив с тремя цветами. Допустим, красный, синий и зеленый. Моя проблема в том, что я не могу понять как при клике на какую-то кнопку каждый из этих трёх элементов приобрел рандомное значение из этого массива. Т.е. изменил бэкграунд. Пыталась вот так: var colors = [ '#ff0000', '#00ff00', '#0000ff' ]; var random_color = colors[ Math.floor(Math.random() * colors.length) ]; document.getElementsByClassName('sq')[0].style.backgroundColor =random_color; Но ничего. Но если использовать вместо class - id, то работает. Помогите, пожалуйтса |
Цитата:
Цвета рандомные могут повторяться? |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .sq{ width: 100px; height: 100px; border: 1px solid grey; } </style> </head> <body> <div class="sq">Элемент 1</div> </body> <script> var colors = [ '#ff0000', '#00ff00', '#0000ff' ]; document.getElementsByClassName('sq')[0].onclick=e=>e.target.style.backgroundColor = colors[ Math.floor(Math.random() * colors.length)]; </script> </html> |
j0hnik, дык
Цитата:
|
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .sq{ width: 100px; height: 100px; border: 1px solid grey; display:inline-block; margin:0 10px; } </style> </head> <body> <!-- © j0hnik //--> <div class="sq">Элемент 1</div> <div class="sq">Элемент 2</div> <div class="sq">Элемент 3</div> <div> <input type="button" value="Какая-то кнопка" id="some_button"/> </div> </body> <script type="text/javascript"> var colors = [ '#f00', '#0f0', '#00f' ]; document.getElementById('some_button').onclick=function(){ [].forEach.call(document.getElementsByClassName('sq'),function(node){ node.style.backgroundColor = colors[ Math.floor(Math.random() * colors.length)]; }); }; </script> </html> |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> body { display: -webkit-flex; display: flex; } .sq{ width: 100px; height: 100px; border: 1px solid grey; } </style> </head> <body> <div class="sq">Элемент 1</div> <div class="sq">Элемент 2</div> <div class="sq">Элемент 3</div> </body> <script> var colors = [ '#ff0000', '#00ff00', '#0000ff' ]; document.getElementsByTagName('body')[0].onclick=e=>e.target.style.backgroundColor = colors[ Math.floor(Math.random() * colors.length)]; </script> </html> |
Dilettante_Pro, в вашем примере кнопки недостает :)
Цитата:
|
Nexus,
независимый вариант - для разнообразия |
Спасибо, уже нашла решение)
<p id="mini"></p> <div class="flex"> <div class="shape square"></div> <div class="shape circle"></div> <div class="shape oval"></div> </div> <div id="foo"> Click</div> $("#foo").click(function () { var colors = [ 'green', 'red', 'blue' ]; var divs = [ 'square', 'circle', 'oval' ]; function compareRandom() { return Math.random() - 0.5; } colors.sort(compareRandom); divs.sort(compareRandom); document.getElementsByClassName(divs[0])[0].style.backgroundColor = colors[0]; document.getElementsByClassName(divs[1])[0].style.backgroundColor = colors[1]; document.getElementsByClassName(divs[2])[0].style.backgroundColor = colors[2]; var r_class = divs[Math.floor(Math.random() * divs.length)]; var r_color = colors[Math.floor(Math.random() * colors.length)]; document.getElementById("mini").innerHTML = "Select " + document.getElementsByClassName(r_class)[0].style.backgroundColor + " " + r_class; document.getElementById("mini").style.color = r_color; $(".shape").click(function () { if (this.style.backgroundColor == document.getElementsByClassName(r_class)[0].style.backgroundColor && ) { alert("yep"); } else { alert("no"); } }) }); |
Часовой пояс GMT +3, время: 05:48. |