隨機顏色和動態改變字體大小
阿新 • • 發佈:2018-09-04
bsp turn 分享 代碼示例 har 分享圖片 utf-8 動態改變 縮小
先看隨機顏色
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>隨機一個顏色</title> <style> #div { width:400px; height: 400px; margin: 50px auto; text-align: center; line-height: 400px; background: red; font-size: 30px; } </style> <script> /* 光的三原色 紅 綠 藍 rgba(255, 255, 255, 1);//li用rgba這種顏色模式,因為都是數字可以隨機 parseInt(Math.random() * 256); */ window.onload = function(){var oDiv = document.getElementById(‘div‘); setInterval(function(){ //用定時器每隔1s換一次背景 oDiv.style.backgroundColor = randomColor(); },1000); } /*--------------隨機顏色函數------------------*/ function randomColor(){ //用字符串拼接 成 rgba(num, num, num, 1); 的形式 因為只要用 + 拼接 結果一定是字符串 ,剛好屬性後面傳入的也是字符串即 backgroundColor =‘rgba(num, num, num, 1)‘var str = ‘rgba(‘ + parseInt(Math.random() * 256)+‘, ‘+parseInt(Math.random() * 256)+‘, ‘+parseInt(Math.random() * 256)+‘, ‘+1 + ‘)‘; return str; } /*--------------隨機顏色函數end------------------*/ </script> </head> <body> <div id="div">div文本</div> </body> </html>
瀏覽器效果:
我們增加些難度,讓div文本這幾個字 每放大6次,再縮小6次,來回重復
代碼示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>隨機一個顏色加文本每放大6次縮小6次</title> <style> #div { width:400px; height: 400px; margin: 50px auto; text-align: center; line-height: 400px; background: red; font-size: 30px; } </style> <script> /* 光的三原色 紅 綠 藍 rgba(255, 255, 255, 1);//li用rgba這種顏色模式,因為都是數字可以隨機 parseInt(Math.random() * 256); */ window.onload = function(){ var oDiv = document.getElementById(‘div‘);//獲取div元素節點 var speed = 5; //每次增加的數 var count = 1; setInterval(function(){ //用定時器每隔1s換一次背景 oDiv.style.backgroundColor = randomColor(); //<1>當前字體大小 var currentFontSize = parseInt(getStyle(oDiv,‘fontSize‘)); //<2>設置新的字體大小 oDiv.style.fontSize = currentFontSize + speed + ‘px‘; //[註] getStyle()只能獲取當前屬性有效值,但是不能用來設置樣式。設置樣式要用節點元素屬性的方法。 if(count % 6 == 0){//如果是6的倍數時,符號反轉一次 speed *= -1; } count++; },1000); } /*--------------隨機顏色函數------------------*/ function randomColor(){ //用字符串拼接 成 rgba(num, num, num, 1); 的形式 因為只要用 + 拼接 結果一定是字符串 ,剛好屬性後面傳入的也是字符串即 backgroundColor =‘rgba(num, num, num, 1)‘ var str = ‘rgba(‘ + parseInt(Math.random() * 256)+‘, ‘+parseInt(Math.random() * 256)+‘, ‘+parseInt(Math.random() * 256)+‘, ‘+1 + ‘)‘; return str; } /*--------------隨機顏色函數end------------------*/ /*---------------封裝的獲取當前有效屬性函數的兼容寫法--------*/ // 瀏覽器兼容寫法 function getStyle(node, styleType){ return node.currentStyle ? node.currentStyle[styleType] : getComputedStyle(node)[styleType]; } /*---------------封裝的獲取當前有效屬性函數的兼容寫法end--------*/ </script> </head> <body> <div id="div">div文本</div> </body> </html>
瀏覽器效果:
隨機顏色和動態改變字體大小