offsetLeft与offsetTop详解

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;}

是不是好了,哈哈

转载于:https://www.cnblogs.com/gongshunkai/p/5839587.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值