1、页面上两个按钮,分别为方块和圆形
2、点击方块按钮后,每在屏幕点击鼠标,就会生成一个100px的黑色方块,方块的中心坐标位于鼠标点击时候的坐标处,点击方块会弹出hello!!,I am block
3、点击圆形按钮后,每在屏幕点击鼠标,就会在屏幕上生成一个100px的黑色正圆,正圆的中心坐标位于鼠标点击时候的坐标处,点击圆形会弹出hello!!,I am circle,再次点击会弹出Goodbye!并在1s的时间内淡出。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
//添加事件
function addHandler(element,type,handler){
if(element.addEventListener){
element.addEventListener(type,handler,false);
}else if(element.attachEvent){
element.attachEvent('on'+type,handler);
}else{
element['on'+type]=handler;
}
}
//画图类
function Picture(radius,f){
}
Picture.prototype.draw=function(radius,f){
document.οnclick=function(e){
var div=document.createElement("div");
var strStyle="position:absolute;width:100px;height:100px;background-color:#000;border-radius:"+radius
+";left:"+(e.clientX-50)+"px;top:"+(e.clientY-50)+"px;"
div.setAttribute("style",strStyle);
document.body.appendChild(div);
return f(div);
}
}
//方块类
function Square(){
}
Square.prototype=new Picture();
Square.prototype.caller=function(o){
addHandler(o,"click",function(e){
e.stopPropagation();
alert("hello!!,I am block");
});
}
//圆形类
function Circle(){
}
Circle.prototype=new Picture();
Circle.prototype.caller=function(o){
var count=true;
addHandler(o,"click",function(e){
e.stopPropagation();
if(count==true){
alert("hello!!,I am circle");
count=false;
}else{
alert("Goodbye!");
var timer=null;
var alpha=100;
var target=0;
clearInterval(timer);
timer=setInterval(function(){
if(alpha<=target){
clearInterval(timer);
}else{
alpha-=10;
o.style.opacity=alpha/100;
o.style.filter='(opacity='+alpha+')';
o.style.filter='(opacity='+alpha+')';
}
},6)
count=true;
}
});
}
//开始执行
function play(type){
if(type=="block"){
var dom=new Square();
dom.draw(0,dom.caller);
}else if(type=="circle"){
var dom=new Circle();
dom.draw("50%",dom.caller);
}
}
window.οnlοad=function(){
var block=document.getElementById("block");
var circle=document.getElementById("circle");
addHandler(block,"click",function(e){
e.stopPropagation();
play("block")
});
addHandler(circle,"click",function(e){
e.stopPropagation();
play("circle");
})
}
</script>
</head>
<body>
<button type="button" id="block">方块</button>
<button type="button" id="circle">圆形</button>
</body>
</html>