单击时将文本的颜色更改为随机颜色(按钮)

Change color of the text on click to random color (Button)

本文关键字:颜色 随机 按钮 文本 单击      更新时间:2023-09-26

我的html工作需要帮助。我对javascript还很陌生,我有一项工作要求我"onclick更改排序列表中文本的颜色,将其更改为随机颜色。"

需要更改的段落是id=p1,到目前为止我得到的只是

<script>
// Random Colors
function randomColors() {
}    
</script>

<div> 
  <button type="button" id="b1" class="button" onclick="randomColors()">Button 1</button>
</div>
Paul Irish在他的网站上有几个javascript的随机颜色生成器的例子。

可以相当简单地实现。。。

示例

function randomize() {
  document.getElementById('p1').style.color = randomColors();
}
// random colors - taken from here:
// http://www.paulirish.com/2009/random-hex-color-code-snippets/
function randomColors() {
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
<div>
  <p id="p1">Hello World</p>
</div>
<button id="b1" onclick="randomize()">Click Me!</button>

HTH

这里有一个很好的,可以保持相同的亮度和饱和度:

function getRndColor() {
    return 'hsl(' + (360 * Math.random()) + ',50%,50%)'; // H,S,L
}