第一个例子:div动起来
讲解:通过随机函数来改变div到父级元素左边的距离和到上面的距离
//样式
#dv{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
}
<input type="button" value="动起来" id="btn1" >
<input type="button" value="停止" id="btn2" >
<div id="dv"></div>
var timer;
my$("btn1").onclick = function () {
//先清除,在添加定时器
clearInterval(timer);
timer = setInterval(function () {
//生成随机数
var x = parseInt(Math.random() * 400 + 1);//1到100随机数
var y = parseInt(Math.random() * 500 + 1);
//设置元素的top值和left值
my$("dv").style.left = x + "px";
my$("dv").style.top = y + "px";
var arr = ["red","green","blue","pink","black","orange","yellow","purple","cyan","gold","grey","hotpink","white"];
var color = parseInt(Math.random()*13);
my$("dv").style.backgroundColor = arr[color];
},200)
my$("btn2").onclick = function () {
clearInterval(timer);
}
}
function my$(id){
return document.getElementById(id);
}
第二个例子:时钟
讲解:通过系统自带的时间函数创建对象,获取当前系统的时间,再用定时器每过1秒执行相应的函数
*{
margin: 0;
padding: 0;
}
body{
background-color: pink;
color: red;
text-align: center;
}
div{
width: 700px;
line-height: 100px;
mar