Good programmer web front-end tutorials will continue to share the front-end javascript exercise series for you.
Math object
1. Write a function to get a hexadecimal random color string (for example: # 20CD4F)
Method:
function f2(){
var str="0123456789abcdef"; var color="#"; for(var i=0;i<6;i++){ var num=Math.floor(Math.random()*str.length); color=color+str[num]; } console.log(color);}f2();
date object
Digital clock
Idea analysis: Name the pictures in time and seconds according to certain rules to facilitate subsequent settings of picture paths according to time
Method:
<img src="img/0.png" alt="" /> <img src="img/0.png" alt="" /> <span>Time</span> <img src="img/0.png" alt="" /> <img src="img/0.png" alt="" /> <span>branch</span> <img src="img/0.png" alt="" /> <img src="img/0.png" alt="" /> <span>second</span></div>
function f1(){ var str=""; //Get all the pictures from the tag and store them in the variable imgid var imgid=document.getElementsByTagName("img"); var oDate = new Date(); //Create time object var h=oDate.getHours(); //Get the current time and seconds separately var fen=oDate.getMinutes(); var miao= oDate.getSeconds(); var h1=h>=10?h:"0"+h; //Guarantees are made up of two bits. var fen1=fen>=10?fen:"0"+fen; var miao1=miao>=10?miao:"0"+miao; str=str+h1+fen1+miao1; //Combine into a new string for(var i=0;i<str.length;i++){ //Traversal string //The analogy src="img/0.png"; imgid[i].src='img/'+str[i]+'.png'; //Set the src path for each image } } setInterval(f1,1000); //The last parameter of the timer is in milliseconds
Encapsulation of functions
Encapsulation: Functions as parameters of objects
eg1:. To determine whether a year is a leap year, format the date to output "2015 | 08 | 24", get the days of a month, judge the days of the difference between the two dates, and get the dates after N days.
var dateUtil = {
isLeapYear:function(year){
if(year%4==0&&year%100!=0 || year%400==0){ return true; } return false;
},
formatDate:function(date,str){
var year = date.getFullYear(); var month = date.getMonth()+1; var day = date.getDate(); if(month < 10){ month = "0"+month; } if(day < 10){ day = "0" + day; } var ss = year+str+month+str+day return ss;
},
getDays:function(date){
var year = date.getFullYear(); var month = date.getMonth()+1; switch(month){ case 2: if(dateUtil.isLeapYear(year)){ return 29; } return 28; break; case 4: case 6: case 9: case 11: return 30; break; default: return 31; }
},
getDiffDays:function(date1,date2){
//Subtraction of two dates yields a difference in milliseconds //Days, hours, minutes and seconds var ss = Math.abs((date2-date1)/1000); var day = Math.floor(ss/24/3600); var hour = Math.floor(ss/3600%24); var minute = Math.floor(ss/60%60); var second = Math.floor(ss%60); return day+"day"+hour+"Time"+minute+"branch"+second+"second";
},
getNDays:function(n){
var oDate = new Date(); oDate.setDate(oDate.getDate()+n); return oDate;
}};
DOM and BOM