首页 前端知识 jQuery位置方法

jQuery位置方法

2024-03-03 11:03:13 前端知识 前端哥 154 392 我要收藏

位置主要有三个: offset()、position()、scrollTop()/scrollLeft()

1. offset() 设置或获取元素偏移

  1. offset() 方法设置或返回被选元素相对于文档的偏移坐标,跟父级没有关系。
  2. offset()方法返回的是一个对象
  3. 该方法有2个属性 left、top 。offset().top  用于获取距离文档顶部的距离,offset().left 用于获取距离文档左侧的距离。
  4. 可以设置元素的偏移:offset({ top: 10, left: 30 });

2. position() 获取元素偏移

  1. position() 方法用于返回被选元素相对于带有定位的父级偏移坐标,如果父级都没有定位,则以文档为准。
  2. 该方法有2个属性 left、top。position().top 用于获取距离定位父级顶部的距离,position().left 用于获取距离定位父级左侧的距离。
  3. 该方法只能获取,不能设置偏移

3. scrollTop()/scrollLeft() 设置或获取元素被卷去的头部和左侧

  1. scrollTop() 方法设置或返回被选元素被卷去的头部。
  2. 不跟参数是获取,参数为不带单位的数字则是设置被卷去的头部。

案例:返回顶部

做法1:$(document).scrollTop(0);

这个效果是直接返回顶部,所以考虑第二种方法。

做法2:带有动画的返回顶部

  1. 核心原理: 使用animate动画返回顶部。
  2. animate动画函数里面有个scrollTop 属性,可以设置位置
  3. 但是是元素做动画,因此 $(“body,html”).animate({scrollTop: 0})。而不是document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body {
height: 2000px;
}
.back {
position: fixed;
width: 50px;
height: 50px;
background-color: pink;
right: 30px;
bottom: 100px;
display: none;
}
.container {
width: 900px;
height: 500px;
background-color: skyblue;
margin: 400px auto;
}
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<div class="back">返回顶部</div>
<div class="container">
</div>
<script>
$(function() {
$(document).scrollTop(100);
// 被卷去的头部 scrollTop() / 被卷去的左侧 scrollLeft()
// 页面滚动事件
var boxTop = $(".container").offset().top;
$(window).scroll(function() {
// console.log(11);
console.log($(document).scrollTop());
if ($(document).scrollTop() >= boxTop) {
$(".back").fadeIn();
} else {
$(".back").fadeOut();
}
});
// 返回顶部
$(".back").click(function() {
// $(document).scrollTop(0);
$("body, html").stop().animate({
scrollTop: 0
});
// $(document).stop().animate({
// scrollTop: 0
// }); 不能是文档而是 html和body元素做动画
})
})
</script>
</body>
</html>
复制

 

参考:黑马

转载请注明出处或者链接地址:https://www.qianduange.cn//article/3166.html
标签
评论
还可以输入200
共0条数据,当前/页
会员中心 联系我 留言建议 回顶部
复制成功!