javascript 为元素绑定事件并获取元素位置

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
    <meta charset="utf-8">

</head>
<body>

<button id="btn1">点击</button>
<script>

(
    function(){
        addEvent(document.getElementById('btn1'),'click',function(e){
            alert("点击了!");
            var point = getPosition(e);
            alert("点击位置:x: " + point.x + " y:" + point.y);
        });
        // 为元素绑定事件
        function addEvent(o,type,fn){
           o.attachEvent ? o.attachEvent('on' + type,fn) : o.addEventListener(type,fn,false);
        }

        function getPosition(ev) {
            ev = ev || window.event;
            var point = {
                x : 0,
                y : 0
            };
            if (ev.pageX || ev.pageY) {
                point.x = ev.pageX;
                point.y = ev.pageY;
            } else {// 兼容ie
                point.x = ev.clientX + document.body.scrollLeft
                        - document.body.clientLeft;
                point.y = ev.clientY + document.documentElement.scrollTop;
            }
            return point;
        }
    }
 )();


</script>
</body>
</html>

你可能感兴趣的:(javascript 为元素绑定事件并获取元素位置)