1. 程式人生 > >如何用原生js給特定元素隨機新增背景色

如何用原生js給特定元素隨機新增背景色

每次做專案都是red,pink,blue,不僅單調乏味,而且充分暴露了自己三級甲等的英語水平,作為一名有理想,積極向上的程式設計師,這是果斷不能忍的事情,今天剛好寫一個用原生js給特定元素隨機新增背景色的方法,瞬間讓單調的生活豐富多彩起來,有了此方法媽媽再也不用擔心我找不到女朋友了。

原始碼:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style type
="text/css">
.box{ height: 200px; width: 200px; background: red; } </style> </head> <body> <div class="box"></div> <button class="btn">點我隨機變化顏色</button> <script type="text/javascript"> var btn = document.querySelector(".btn"
); var box = document.querySelector(".box"); btn.onclick = function () { randColor(box) } function randColor(element) { //隨機改變背景色 var ranColor = '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6); element.style.background = ranColor; }
</script> </body> </html>

線上效果