前些天答小米笔试题,本人由于身体原因,只能在答了一半题之后,弃题而不顾,奔向厕所,现在隐隐回忆起当时的一道题,觉得挺有意思,就拿出来写写。
题目要求:实现点击相应按钮画圆和方块,都旋转,变小。圆和方块继承一个主类Draw,每个元素以鼠标点击的中心为准。 我记不清具体实现什么效果,但主要是继承!!!
我在这里写一种自己的实现方法。
样式:
<style type="text/css">
*{
margin:0;
padding:0;
}
button{
width:300px;
height:30px;
line-height: 30px;
border:0;
color:white;
text-align: center;
display: inline-block;
position: absolute;
top:30px;
}
#parent{
width:100%;
height:500px;
margin-top: 100px;
background-color: #ccc;
position: relative;
}
.circle{
width:100px;
height:100px;
background-color: #078600;
border-radius:50%;
position: absolute;
transition:width 2s, height 2s, transform 2s;
}
.square{
width:100px;
height:100px;
background-color: #a40004;
position: absolute;
transition:width 2s, height 2s, transform 2s;
}
</style>
主体元素:
<body>
<button style="background:#0acf00; left:300px;">DRAW CIRCLE</button>
<button style="background:#fd0006; left:800px;">DRAW SQUARE</button>
<div id="parent"></div>
</body>
js实现继承及效果:
<script type="text/javascript">
var buts = document.getElementsByTagName('button');
var pat = document.getElementById('parent');
</pre><pre name="code" class="javascript">// 创建一个主类,实现创建圆和方块的方法
function Draw(){};
Draw.prototype = {
constructor : Draw,
// 以event为参数,作为事件源,侦测鼠标位置,确定div的创建位置。
createCircle : function(event){
var circle = document.createElement("div");
circle.className = "circle";
circle.style.left = event.clientX - pat.offsetLeft - 50 +"px";
circle.style.top = event.clientY - pat.offsetTop - 50 +"px";
return circle;
},
createSquare : function(){
var square = document.createElement("div");
square.className = "square";
square.style.left = event.clientX - pat.offsetLeft - 50 +"px";
square.style.top = event.clientY - pat.offsetTop - 50 +"px";
return square;
}
}
</pre><pre name="code" class="javascript">// 圆和方块类
function Circle(){};
function Square(){};
// 实现继承
Circle.prototype = new Draw();
Square.prototype = new Draw();
buts[0].onclick = function(){
this.style.backgroundColor = "#000";
buts[1].style.backgroundColor = "#fd0006";
pat.onclick = function(e){
var event = e || window.e;
var newCircle = new Circle();
var cc = newCircle.createCircle(event);
pat.appendChild(cc);
setTimeout(function(){
cc.style.width = 10+"px";
cc.style.height = 10+"px";
cc.style.transform = "rotateX(360deg)";
},0);
}
}
buts[1].onclick = function(){
this.style.backgroundColor = "#000";
buts[0].style.backgroundColor = "#0acf00";
pat.onclick = function(e){
var event = e || window.e;
var newSquare = new Square();
var ss = newSquare.createSquare(event);
pat.appendChild(ss);
setTimeout(function(){
ss.style.width = 10+"px";
ss.style.height = 10+"px";
ss.style.transform = "rotateY(360deg)";
},0);
}
}
</script>