最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change color of the text on click to random color (Button) - Stack Overflow

programmeradmin4浏览0评论

I need help with my html work. I'm pretty new to javascript and I had a work asking me to "onclick changes the color of the text in our ordered list to change to a random color."

The paragraph that needs to be changed is id=p1, and so far all I got is

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

and

<div> 
  <button type="button" id="b1" class="button" onclick="randomColors()">Button 1</button>
</div>

I need help with my html work. I'm pretty new to javascript and I had a work asking me to "onclick changes the color of the text in our ordered list to change to a random color."

The paragraph that needs to be changed is id=p1, and so far all I got is

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

and

<div> 
  <button type="button" id="b1" class="button" onclick="randomColors()">Button 1</button>
</div>
Share Improve this question edited Mar 30, 2015 at 23:54 Jawa 2,3326 gold badges34 silver badges39 bronze badges asked Mar 30, 2015 at 21:43 Anthony Anthony 31 gold badge1 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

Paul Irish has a few examples of a random color generator for javascript on his website here.

Which, can be implemented fairly simply...

Example

function randomize() {
  document.getElementById('p1').style.color = randomColors();
}


// random colors - taken from here:
// http://www.paulirish./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

here is a nice one that keeps the same lightness and saturation:

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

评论列表(0)

  1. 暂无评论