codeing or artist ?
记得大学第一节编程课,教授说,"如果一件事儿有对错,那么是科学。如果有美丑好坏,那么是艺术。" 一个能顺利运行还能让人阅读时体验思维美妙的代码,就是艺术和科学的结合。能运行的程序并不是好程序,能当作文章来读的才是。在我看来代码是一种特殊的文体,程序猿其实会写诗。
<style>
html,body{margin:0;padding:0;}
.d1{margin-left:40px;background:red;width:2000px;height:100px;position:relative;}
.d2{margin-left:40px;background:blue;width:1000px;height:80px;}
</style>

<div id="d1" class="d1">
    <div id="d2" class="d2"></div>
</div>
function getWindow( elem ) {
    return mylibs.isWindow( elem ) ?
        elem :
        elem.nodeType === 9 ?
            elem.defaultView || elem.parentWindow :
            false;
};

var mylibs = {
    isWindow: function( obj ) {
        return obj != null && obj == obj.window;
    },
    //获取元素在浏览器中的绝对位置
    offset:function(elem){
        var docElem, win, clientTop, clientLeft, scrollTop, scrollLeft,
            box = { top: 0, left: 0 },
            doc = elem && elem.ownerDocument;

        if ( !doc ) {
            return;
        }

        docElem = doc.documentElement;
        //黑莓5 ios3(iphoe) 没有getBoundingClientRect
        if ( typeof elem.getBoundingClientRect !== "undefined" ) {
            box = elem.getBoundingClientRect();
        }
        win = getWindow( doc );

        clientTop  = docElem.clientTop  || document.body.clientTop  || 0;
        clientLeft = docElem.clientLeft || document.body.clientLeft || 0;
        scrollTop  = win.pageYOffset || docElem.scrollTop;
        scrollLeft = win.pageXOffset || docElem.scrollLeft;
        return {
            top: box.top  + scrollTop  - clientTop,
            left: box.left + scrollLeft - clientLeft
        };
    }
};

//调用:
document.getElementById('d2').onclick = function(){
    alert(mylibs.offset(this).left);
};

 

posted on 2016-08-31 18:11  codeing-or-artist-??  阅读(410)  评论(0编辑  收藏  举报