当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery获取随机颜色的实例代码

jQuery获取随机颜色的实例代码

2019年06月05日  | 移动技术网IT编程  | 我要评论

1.js

//获取十六进制颜色 
  function randomcolor1(){ 
   var r = math.floor(math.random()*256); 
   var g = math.floor(math.random()*256); 
   var b = math.floor(math.random()*256); 
   if(r < 16){ 
    r = "0"+r.tostring(16); 
   }else{ 
    r = r.tostring(16); 
   } 
   if(g < 16){ 
    g = "0"+g.tostring(16); 
   }else{ 
    g = g.tostring(16); 
   } 
   if(b < 16){ 
    b = "0"+b.tostring(16); 
   }else{ 
    b = b.tostring(16); 
   } 
   return "#"+r+g+b; 
  } 
  $("h3").css("color",randomcolor1()); 

2.html

.<h3>获取任意颜色</h3> 

效果:

下面在看一段代码关于js几种生成随机颜色方法

<!doctype html>
<html>
<head lang="en">
 <meta charset="utf-8">
 <title></title>
</head>
<body>
  <button id="btn1">调用第一种</button>
  <button id="bnt2">调用第二种</button>
  <button id="btn3">调用第三种</button>
  <script>
   var btn1=document.getelementbyid('btn1');
   btn1.onclick=function(){
    document.body.style.background=bg1()
   };
   var btn2=document.getelementbyid('bnt2');
   btn2.onclick=function(){
    document.body.style.background=bg2();
   };
   var btn3=document.getelementbyid('btn3');
   btn3.onclick=function(){
    document.body.style.background=bg3();
   };
   function bg1(){
    return '#'+math.floor(math.random()*256).tostring(10);
   }
   function bg2(){
    return '#'+math.floor(math.random()*0xffffff).tostring(16);
   }
   function bg3(){
    var r=math.floor(math.random()*256);
    var g=math.floor(math.random()*256);
    var b=math.floor(math.random()*256);
    return "rgb("+r+','+g+','+b+")";//所有方法的拼接都可以用es6新特性`其他字符串{$变量名}`替换
   }
  </script>
</body>
</html>

总结

以上所述是小编给大家介绍的jquery获取随机颜色的实例代码,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网