1.offset()
方法描述:相对页面左上角的坐标。
需求描述:获取div相对页面左上角的坐标
.box { width: 100px; height: 100px; background: coral; }
<div class="box"></div>
var offset = $('.box').offset(); console.log(offset.left, offset.top);
2.position()
方法描述:相对于父元素左上角的坐标。
需求描述:获取div相对于父元素左上角的坐标
.box-container { width: 300px; height: 300px; background: pink; position: absolute; left: 20px; top: 20px; }
.box { width: 100px; height: 100px; background: coral; position: absolute; left: 20px; top: 20px; }
<div class="box-container"> <div class="box"></div> </div> var offset = $('.box').position(); console.log(offset.left, offset.top);
3.scrollLeft()
设置页面滚动条滚动到指定位置(兼容chrome和IE)
$('body,html').scrollLeft(60);
需求描述:设置页面的宽度为2000px,设置滚动条的X轴坐标为300px,要求兼容各种浏览器
$('body').css('width', '2000px'); $('html,body').scrollLeft(300);
4. scrollTop()
方法描述:读取/设置滚动条的Y坐标,该方法读写合一。
读取页面滚动条的Y坐标(兼容chrome和IE)
$('body,html').scrollTop(60);
$('body').css('height', '2000px'); $('html,body').scrollTop(300);