>  기사  >  웹 프론트엔드  >  js에서 임의의 색상을 생성하는 여러 가지 방법

js에서 임의의 색상을 생성하는 여러 가지 방법

高洛峰
高洛峰원래의
2016-10-15 16:10:36974검색

<!DOCTYPE html>
<html>
<head>
    <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(&#39;btn1&#39;);
         btn1.onclick=function(){
             document.body.style.background=bg1()
         };
         var btn2=document.getElementById(&#39;bnt2&#39;);
         btn2.onclick=function(){
             document.body.style.background=bg2();
         };
         var btn3=document.getElementById(&#39;btn3&#39;);
         btn3.onclick=function(){
             document.body.style.background=bg3();
         };
         function bg1(){
             return &#39;#&#39;+Math.floor(Math.random()*256).toString(10);
         }
         function bg2(){
             return &#39;#&#39;+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+&#39;,&#39;+g+&#39;,&#39;+b+")";//所有方法的拼接都可以用ES6新特性`其他字符串{$变量名}`替换
         }
     </script>
</body>
</html>


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.