offset():到屏幕的距离,不用管父级有没有相对定位
positon():到定位的父级元素的距离
div1没有定位时,两者结果相同
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#div1{
width: 200px;height: 200px;background-color: red;margin: 100px;
}
#div2{
width: 100px;height: 100px;background-color: yellow;
position: relative;left: 50px;top: 50px;
}
</style>
<div id="div1">
<div id="div2"></div>
</div>
<script type="text/javascript">
console.log($('#div2').offset().left);//150
console.log($('#div2').position().left);//150
</script>
给div1相对定位position:relative
<script type="text/javascript">
console.log($('#div2').offset().left);//150
console.log($('#div2').position().left);//50
</script>
点击跟随鼠标案例:
<div id="box" style="width: 100px;height: 100px;background-color: red;position: relative;"></div>
<script type="text/javascript">
var W = $('#box').width()/2,
H = $('#box').height()/2;
$(document).click(function(event){
// $('#box').offset({left:event.pageX-W,top:event.pageY-H});//没有运动效果
$('#box').animate({left:event.pageX-W,top:event.pageY-H});
})
筋斗云效果:利用li标签相对父级的offsetLeft
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="js/jquery-3.2.1.js" type="text/javascript" charset="utf-8"></script>
<style>
*{margin: 0; padding: 0;}
ul {list-style:none;}
body {
background-color: #000;
}
.nav {
width: 800px;
height: 42px;
background:url("images/rss.png") no-repeat right center #fff;
margin: 100px auto;
border-radius: 5px;
position: relative;
}
.cloud {
width: 83px;
height: 42px;
position: absolute;
top: 0;
left: 0;
background: url(images/cloud.gif) no-repeat;
}
.nav ul {
position: absolute;
top: 0;
left: 0;
}
.nav li {
float: left;
width: 83px;
height: 42px;
line-height: 42px;
text-align: center;
color: #000;
cursor: pointer;
}
</style>
</head>
<body>
<div class="nav" id="nav">
<span class="cloud" id="cloud"></span>
<ul>
<li>首页新闻</li>
<li>师资力量</li>
<li>活动策划</li>
<li>企业文化</li>
<li>招聘信息</li>
<li>公司简介</li>
<li>上海校区</li>
<li>广州校区</li>
</ul>
</div>
</body>
<script type="text/javascript">
var target,current=0;
$('#nav li').hover(function(){
// target = this.offsetLeft;
target = $(this).position().left;
$('#cloud').stop().animate({left:target});
},function(){
$('#cloud').stop().animate({left:current});
})
.click(function(){
current = this.offsetLeft;
})
</script>
</html>