JQuery 提供三个确定元素位置的实用方法;
offset 返回一个对象,其中包含元素左上角与document 左上角的相对位置。
position 返回一个对象,其中包含元素左上角与该元素第一个定位的双亲元素(offSetParent)左上角的相对位置。position 方法提供的位置信息是相对于offsetParent 而不是相对于document 的。
offsetParent 返回一个jQuery对象,其中包含元素的offsetParent.
下面举例如何使用position 来进行元素相对定位。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
var handler = function(e){
var $bubble = $('.bubble').position();
//alert('top '+$bubble.top);
//alert('left '+$bubble.left);
$('.tooltipWrapper').css({
//display : 'none',
position : 'absolute',
top: $bubble.top + 16+ 8,
left: $bubble.left +80
}).toggleClass('displays');
if($('.tooltipWrapper').hasClass('displays')){
$('.tooltipWrapper').show();
}else{
$('.tooltipWrapper').hide();
}
};
$("#bubbleId").click(handler);
//var $foo = jQuery('.foo');
//var fooPosition = $foo.position();
});
</script>
<style>
.foo{
withd: 300px;
height: 100px;
border: 1px solid red;
padding: 5px;
}
.tooltip{
border: 1px solid black;
padding: 5px;
background-color: #fff;
width : 300px;
}
.bubble {
margin: 10px 10px 10px 100px;
}
.tooltipWrapper{
position : 'absolute';
display : none;
}
.arrowup{
margin : 0px 0px -5px 0px;
}
</style>
</head>
<body>
<div class ="foo"> An existing elements.</div>
<div class = "bubble">
<span id="bubbleId"> <a href="#"> <img src="../content/arrowup.jpg" /></a> </span>
</div>
<div class="tooltipWrapper">
<div class="arrowup"><span id="arrowup" > <img src="../content/arrowdown.JPG" /> </span> </div>
<div class ="tooltipDiv tooltip" >
<p>
This is the context. This is the context. This is the context. This is the context. This is the context.
This is the context. This is the context. This is the context. This is the context. This is the context.
This is the context. This is the context. This is the context. This is the context. This is the context.
This is the context. This is the context. This is the context. This is the context. This is the context.
</p>
</div>
</div>
</body>
</html>