用offsetLeft和offsetTop取得一个节点的绝对位置的时候, 如果父节的位置如果是设置position: relative;并且设置了margin和padding的宽度(比如都是1em), 这样得到的结果就不正确(IE不正确), 有什么办法可以解决?下面是测试代码:<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function getPosition(obj){
var topValue = 0, leftValue = 0;
while (obj) {
leftValue += obj.offsetLeft;
topValue += obj.offsetTop;
obj = obj.offsetParent;
}
return {
left: leftValue,
top: topValue
};
}
</script>
<style type="text/css">
* {
border: 0;
margin: 0;
padding: 0;
}
#div1 {
padding: 50px;
}
#div2 {
position: relative;
margin: 20px;
padding: 50px;
background: red;
}
#div3 {
height: 50px;
width: 400px;
background: #ccc;
padding: 20px;
}
#cursor {
position: absolute;
background-color: yellow;
width: 50px;
z-index: 1000;
}
</style>
</head>
<body>
<div id="div1">
<div id="cursor">Cursor</div>
<div id="div2">
<br>div2<br><br>
<div id="div3" onClick="moveCursor(this);">div3 - cursor should be moved to here</div>
</div>
<script type="text/javascript">
var cursor = document.getElementById('cursor');
var mainDiv = document.getElementById("div2");
move(cursor, mainDiv);
function moveCursor(cell){
var position = getPosition(cell);
cursor.style.top = position.top + "px";
cursor.style.left = position.left + "px";
}
</script>
</div>
</body>
</html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function getPosition(obj){
var topValue = 0, leftValue = 0;
while (obj) {
leftValue += obj.offsetLeft;
topValue += obj.offsetTop;
obj = obj.offsetParent;
}
return {
left: leftValue,
top: topValue
};
}
</script>
<style type="text/css">
* {
border: 0;
margin: 0;
padding: 0;
}
#div1 {
padding: 50px;
}
#div2 {
position: relative;
margin: 20px;
padding: 50px;
background: red;
}
#div3 {
height: 50px;
width: 400px;
background: #ccc;
padding: 20px;
}
#cursor {
position: absolute;
background-color: yellow;
width: 50px;
z-index: 1000;
}
</style>
</head>
<body>
<div id="div1">
<div id="cursor">Cursor</div>
<div id="div2">
<br>div2<br><br>
<div id="div3" onClick="moveCursor(this);">div3 - cursor should be moved to here</div>
</div>
<script type="text/javascript">
var cursor = document.getElementById('cursor');
var mainDiv = document.getElementById("div2");
move(cursor, mainDiv);
function moveCursor(cell){
var position = getPosition(cell);
cursor.style.top = position.top + "px";
cursor.style.left = position.left + "px";
}
</script>
</div>
</body>
</html>
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货