codeing or artist ?
记得大学第一节编程课,教授说,"如果一件事儿有对错,那么是科学。如果有美丑好坏,那么是艺术。" 一个能顺利运行还能让人阅读时体验思维美妙的代码,就是艺术和科学的结合。能运行的程序并不是好程序,能当作文章来读的才是。在我看来代码是一种特殊的文体,程序猿其实会写诗。

offsetLeft与offsetTop使用方法一样,只是一个是找距离定位父级(position:relative)左边的距离,一个是找距离定位父级上边的距离

没有定位则找body,我们还是看看ie7以下的情况吧。

先看div都设置了宽高的情况:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
body{margin:0;padding:0;}
#d1{width:200px;height:200px;padding:50px;background:red;}
#d2{width:100px;height:100px;padding:50px;background:blue;}
#d3{width:100px;height:100px;background:yellow;}
</style>
</head>
<body>
<div id="d1">
    <div id="d2">
        <div id="d3"></div>
    </div>
</div>
<script>

var dom = document.getElementById('d3');
alert(dom.offsetLeft);
</script>
</body>
</html>

没有设置定位,ie7下竟然是50px,是不是很诡异:

我们设置一下定位试试看:

#d2{width:100px;height:100px;padding:50px;background:blue;position:relative;}

没有问题,依旧是50px

 

继续测试,我们把div的宽高去掉:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
body{margin:0;padding:0;}
div{padding:50px;}
#d1{background:red;}
#d2{background:blue;position:relative;}
#d3{background:yellow;}
</style>
</head>
<body>
<div id="d1">
    <div id="d2">
        <div id="d3"></div>
    </div>
</div>
<script>

var dom = document.getElementById('d3');
alert(dom.offsetLeft);
</script>
</body>
</html>

在ie7下居然是100px,我明明设置了定位啊,怎么解决呢?

于是改一下样式,在#d3上也加上定位:

#d2{background:blue;position:relative;}
#d3{background:yellow;position:relative;}

是不是好了,哈哈

posted on 2016-09-04 16:10  codeing-or-artist-??  阅读(478)  评论(0编辑  收藏  举报