1. 尺寸相关
我们可以使用
$ele.width()
和$ele.height()
方法来快速读取和设置元素的宽度和高度,获取的值是不带单位的 number 类型。
<style>
.box {
width: 200px;
height: 200px;
padding: 20px;
background-color: #f00;
}
</style>
<body>
<div class="box"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var $box = $(".box");
console.log("获取width", $box.width()); // 200
console.log("获取height", $box.height()); // 200
$box[0].onclick = function(){
// 赋值时可以带单位,也可以不带单位
$box.width("300px");
$box.height(300);
}
</script>
</body>
2. 位置相关
2.1 offset
此方法可用于获取或设置元素相对于文档的位置。更改位置是通过调节元素的 top 属性和 left 属性达成的,为此元素需要有定位属性。如果元素没有定位属性,那么此操作会为元素添加 relative 定位属性。
<style>
.container {
position: relative;
margin: 50px;
padding: 50px;
width: 300px;
border: 20px solid #00f;
}
.box {
margin: 20px;
width: 50px;
height: 50px;
background-color: #f00;
}
</style>
<body>
<div class="container">
<div class="box"></div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var $box = $(".box");
console.log("获取元素与页面的上左边距", $box.offset()); // { top: 120, left: 120 }
$box.click(function(){
// 设置元素与页面的上左边距各为 50
$box.offset({
top: 50,
left: 50
})
})
</script>
</body>
2.2 scrollTop/scrollLeft
用于获取匹配元素相对滚动条上左位置的偏移。此方法对可见和隐藏元素均有效。这两个属性可以添加在 animate 动画中,实现动画效果。
<style>
body {
width: 3000px;
height: 3000px;
}
</style>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var $html = $("html");
window.onscroll = function (){
console.log("页面卷入上左边距", {
top: $html.scrollTop(),
left: $html.scrollLeft()
});
}
window.onclick = function (){
$("html").animate({
scrollTop: 0,
scrollLeft: 0
}, 1000, "swing")
}
</script>
</body>
3. 多库共存
此处多库共存指的是:jQuery 占用了$ 和 jQuery 这两个变量。当在同一个页面中引用了其他插件库中也用到了 $。那么,为了保证每个库都能正常使用,需要使用
$.noConflict()
方法让 jQuery 释放对 $ 的控制权,让其他库能够使用 $ 符号,达到多库共存的目的。