(JQuery)偏移量()坐标?

(JQuery)偏移量()坐标?,jquery,Jquery,offset()似乎返回元素相对于文档的当前坐标。好的但是当我尝试使用offset(value)来设置元素的cordinate时,它是相对于元素的当前位置而不是文档来设置的 在示例代码中,我尝试将div2放置在div1的相同位置 代码: div{边距底部:2px;高度:70px} .red{背景色:red} .blue{背景色:blue} .green{背景色:绿色} .orange{背景色:orange} .pink{背景色:pink} .msg{背景色:天蓝色;边框:1px纯黑色;边框半径

offset()似乎返回元素相对于文档的当前坐标。好的但是当我尝试使用offset(value)来设置元素的cordinate时,它是相对于元素的当前位置而不是文档来设置的

在示例代码中,我尝试将div2放置在div1的相同位置

代码:


div{边距底部:2px;高度:70px}
.red{背景色:red}
.blue{背景色:blue}
.green{背景色:绿色}
.orange{背景色:orange}
.pink{背景色:pink}
.msg{背景色:天蓝色;边框:1px纯黑色;边框半径:5px;显示:无}
$(函数(){
$(“.msg”).offset($(.blue”).offset()).slideDown();
});
试验

问题是因为您首先隐藏了
.div1
,从而使其偏移量无法访问。按以下方式更改您的代码,它将正常工作:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html> 

<style>

div{margin-bottom: 2px; height: 70px}
.red{background-color: red}
.blue{background-color: blue}
.green{background-color: green}
.orange{background-color: orange}
.pink{background-color: pink}

.msg{background-color: skyblue; border: 1px solid black; border-radius: 5px; display: none}
</style>

<script type="text/javascript" src="/scripts/jquery-1.6.2.min.js"></script>
<script>
$(function(){   
    $(".msg").offset( $(".blue").offset() ).slideDown(); 

});
</script>

<body>

<div class="red"></div>
<div class="blue"></div>
<div class="green"></div>
<div class="orange"></div>
<div class="pink"></div>

<div class="msg">
    TEST
</div>

</body>

</html>

我已经在JSFIDLE中测试过这个功能,但是由于他们正在更改主机,目前无法链接到它。

发布您的HTML和CSS
.offset()
执行它应该执行的操作,而您的CSS可能会产生干扰。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html> 

<style>

div{margin-bottom: 2px; height: 70px}
.red{background-color: red}
.blue{background-color: blue}
.green{background-color: green}
.orange{background-color: orange}
.pink{background-color: pink}

.msg{background-color: skyblue; border: 1px solid black; border-radius: 5px; display: none}
</style>

<script type="text/javascript" src="/scripts/jquery-1.6.2.min.js"></script>
<script>
$(function(){   
    $(".msg").offset( $(".blue").offset() ).slideDown(); 

});
</script>

<body>

<div class="red"></div>
<div class="blue"></div>
<div class="green"></div>
<div class="orange"></div>
<div class="pink"></div>

<div class="msg">
    TEST
</div>

</body>

</html>
$(".div2").offset( $(".div1").offset() ).slideDown();
$(".div1").hide();