目录
素材已经同步更新:jQueryStudy: jQuery学习仓库 - Gitee.com
1. jQuery 尺寸、位置操作
1.1 jQuery 尺寸
- 以上参数为空,则是获取相应值,返回的是数字型。
- 如果参数为数字,则是修改相应值。
- 参数可以不必写单位。
$(function() {
// 1. width() / height() 获取设置元素 width和height大小
console.log($("div").width());
// $("div").width(300);
// 2. innerWidth() / innerHeight() 获取设置元素 width和height + padding 大小
console.log($("div").innerWidth());
// 3. outerWidth() / outerHeight() 获取设置元素 width和height + padding + border 大小
console.log($("div").outerWidth());
// 4. outerWidth(true) / outerHeight(true) 获取设置 width和height + padding + border + margin
console.log($("div").outerWidth(true));
})
1.2 jQuery 位置
位置主要有三个: offset()、position()、scrollTop()/scrollLeft()
1. offset() 设置或获取元素偏移
- offset() 方法设置或返回被选元素相对于文档的偏移坐标,跟父级没有关系。
- 该方法有2个属性 left、top 。offset().top 用于获取距离文档顶部的距离,offset().left 用于获取距离文档左侧的距离。
- 可以设置元素的偏移:offset({ top: 10, left: 30 });
2. position() 获取元素偏移
- position() 方法用于返回被选元素相对于带有定位的父级偏移坐标,如果父级都没有定位,则以文档为准。
- 该方法有2个属性 left、top。position().top 用于获取距离定位父级顶部的距离,position().left 用于获取距离定位父级左侧的距离。
- 该方法只能获取。
3. scrollTop()/scrollLeft() 设置或获取元素被卷去的头部和左侧
- scrollTop() 方法设置或返回被选元素被卷去的头部。
- 不跟参数是获取,参数为不带单位的数字则是设置被卷去的头部。
$(function() {
// 1. 获取设置距离文档的位置(偏移) offset
console.log($(".son").offset());
console.log($(".son").offset().top);
// $(".son").offset({
// top: 200,
// left: 200
// });
// 2. 获取距离带有定位父级位置(偏移) position 如果没有带有定位的父级,则以文档为准
// 这个方法只能获取不能设置偏移
console.log($(".son").position());
// $(".son").position({
// top: 200,
// left: 200
// });
})
案例:带有动画的返回顶部
素材已经同步更新:jQueryStudy: jQuery学习仓库 - Gitee.com
- 核心原理: 使用animate动画返回顶部。
- animate动画函数里面有个scrollTop 属性,可以设置位置
- 但是是元素做动画,因此 $(“body,html”).animate({scrollTop: 0})
$(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元素做动画
})
})