var div=document.getElementById("点击对象")
点击对象.addEventListener("click",clickHandler);
function clickHandler(e) {
e=e || window.event;
点击时的变化}
点击时找到数组里的元素
function clickHandler(e) {
e=e || window.event;
var index=arr.indexOf(this);
}
侦听事件要清除this.removeEventListener
点击按钮随机添加div
document.body.innerHTML+="<button id='bn'>添加div</button>";
var bn=document.getElementById("bn");
bn.addEventListener("click",clickHandler);
var i=0;
function clickHandler(e) {
e=e || window.event;
addDiv();
i++;
bn=document.getElementById("bn");
bn.addEventListener("click",clickHandler);
}
function addDiv() {
document.body.innerHTML+="<div id='div"+i+"'></div>";
var div=document.getElementById("div"+i);
div.style.position="absolute";
var w=randomWH();
div.style.width=w+"px";
div.style.height=w+"px";
div.style.backgroundColor=randomColor();
var position=getRandomPosition(w);
div.style.left=position.left;
div.style.top=position.top;
console.log(position)
}
function randomColor(){
var str="#";
for(var i=0;i<3;i++){
var col=Math.floor(Math.random()*256).toString(16);
if(col.length<2){
col="0"+col;
}
str+=col;
}
return str;
}
function randomWH() {
return Math.floor(Math.random()*350+50);
}
function getRandomPosition(w) {
var position={};
position.left=Math.floor(Math.random()*(document.documentElement.clientWidth-w))+"px";
position.top=Math.floor(Math.random()*(document.documentElement.clientHeight-w))+"px";
return position;
按钮倒计时
<button id="bn" disabled>进入(10)</button>
var i=9;
var id=setInterval(animation,1000);
var bn=document.getElementById("bn");
function animation() {
bn.innerHTML="进入("+i+")";
i--;
if(i<0){
clearInterval(id);
bn.innerHTML="进入";
bn.disabled=false;
}
}