元素定位之相对定位

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>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值