# 叶落为重生每片落下的叶子都是为了下一次的涅槃...^_^

## 【自己给自己题目做】之一：椭圆可点击区域

【题一】

1. 常用dom操作和简单事件机制（用类库比如jq也算）
2. 简单数学知识（椭圆公式，坐标是否在椭圆区域的判断）
3. 数学模型到编程实践的简单转换

<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<style>
body{
font-family:Microsoft Yahei;
}
.doc {
width: 804px;
margin: 0 auto;
}
#cont {
border: 2px solid #999;
height: 600px;
position: relative;
}
.dot {
position: absolute;
width:1px;
height: 1px;
overflow: hidden;
font-size:0;
line-height: 0;
background: #333;
}
</style>

<body>
<div class="doc">
<h4>【题一】</h4>
<p>

<div id="cont"></div>
</div>

<script>
;(function () {
var win = window,
doc = document,
OFFSET;

function _bind (el, ev, fn) {
return el.addEventListener ? el.addEventListener(ev, fn, false) : el.attachEvent('on'+ev, function () { fn.call(el); });
}
function _$(id) { return doc.getElementById(id) || id; } function _drawElipse (id, a, b) { var el = _$(id);
var docfrag = doc.createDocumentFragment();
for (var i = 0; i < 360; i ++) {
var dot = doc.createElement('div');
dot.className = 'dot';

var l = a*Math.sin(i) + (el.offsetWidth - 4)/2,
t = b*Math.cos(i) + (el.offsetHeight - 4)/2;

dot.style.left = l + 'px';
dot.style.top = t + 'px';

docfrag.appendChild(dot);
}
el.appendChild(docfrag);
}

function offset (el) {
var width = el.offsetWidth,
height = el.offsetHeight,
top = el.offsetTop,
left = el.offsetLeft;
while (el = el.offsetParent) {
top = top + el.offsetTop;
left = left + el.offsetLeft;
}

return {
top: top,
left: left,
height: height,
width: width
}
}

function clickCheck (e) {
e = e || win.event;
var tar = e.target || e.srcElement,
x = e.clientX + doc.body.scrollLeft + doc.documentElement.scrollLeft - OFFSET.left - (tar.offsetWidth/2),
y = e.clientY + doc.body.scrollTop + doc.documentElement.scrollTop - OFFSET.top - (tar.offsetHeight/2);

var r = Math.pow((x/100), 2) + Math.pow((y/80), 2);
console && console.log(x, y, r);
if (r < 1) {
}
}

function __init() {
_drawElipse('cont', 100, 80);

var el = _\$('cont');
OFFSET = offset(el);
_bind(el, 'click', clickCheck);
}
__init();
})();
</script>
</body>
</html>
View Code

 1         function clickCheck (e) {
2                 e = e || win.event;
3                 var tar = e.target || e.srcElement,
4                     x = e.clientX + doc.body.scrollLeft + doc.documentElement.scrollLeft - OFFSET.left - (tar.offsetWidth/2),
5                     y = e.clientY + doc.body.scrollTop + doc.documentElement.scrollTop - OFFSET.top - (tar.offsetHeight/2);
6
7                 var r = Math.pow((x/100), 2) + Math.pow((y/80), 2);
8                 console && console.log(x, y, r);
9                 if (r < 1) {
11                 }
12             }    

-------------------------------------

posted on 2013-07-13 14:57  岑安  阅读(3923)  评论(8编辑  收藏  举报