一 获取元素尺寸
1)基本语法
$('div').width();//1 得到:元素内容宽度
$('div').innerWidth();//2 得到:元素内容宽度 + padding
$('div').outerWidth();//3 得到:元素内容宽度 + padding + border
$('div').outerWidth(true);//4 得到:元素内容宽度 + padding + border + margin
2)注意点
//1 参数为空 是获取值 返回值为数字类型 //2 参数为数字 就是设置值 //3 参数不用带单位
知识梳理
//1 offset() 相对于 文档的偏移量 和父级没有关系 [ 可以 获取 和 设置 ] //2 position() 相对于 带有父级定位的元素偏移量 如果父级都没有定位, 则以文档为准 [ 只能获取 ]
一 获取文档元素
1)基于文档的偏移 [ offset() ]
// 获取值
console.log($('div').offset());// {top: 10, left: 18}
console.log($('div').offset().top);//10
console.log($('div').offset().left);//18
// 设置值
$('div').offset({top:200,left:200});
//1 它是相对于文档的偏移 和父级没有关系
//2 有top 和 left 两个属性 获取距离文档顶部和左侧的距离
2)基于父级的偏移 [ position() ]
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>获取元素偏移</title>
<script src="jquery.min.js"></script>
<style>
body {
padding: 0;
margin: 0;
}
.father {
position: absolute;
800px;
height: 800px;
background: pink;
padding: 50px;
margin: 50px;
}
.son {
300px;
height: 300px;
padding: 10px;
border: solid 2px red;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
console.log($('.son').offset()); // {top: 100, left: 100} //基于文档定位
console.log($('.son').position()); // {top: 50, left: 50} //基于父级定位
</script>
</body>
</html>
二 设置 或 获取 元素被卷去的头部和左侧
scrollTop() scrollLeft()
//1 不带参数是获取
//2 带参数是设置 不用写单位
二 事件处理
//2 事件处理 on() 绑定事件 $("div").on({ click:function () { $(this).css('background','red'); },//绑定事件1 mouseenter:function () { $(this).css('background','pink'); },//绑定事件2 onmouseleave:function () { $(this).css('background','green'); }//绑定事件3 });
知识梳理
//1 offset() 相对于 文档的偏移量 和父级没有关系 [ 可以 获取 和 设置 ] //2 position() 相对于 带有父级定位的元素偏移量 如果父级都没有定位, 则以文档为准 [ 只能获取 ]
一 获取文档元素
1)基于文档的偏移 [ offset() ]
// 获取值
console.log($('div').offset());// {top: 10, left: 18}
console.log($('div').offset().top);//10
console.log($('div').offset().left);//18
// 设置值
$('div').offset({top:200,left:200});
//1 它是相对于文档的偏移 和父级没有关系
//2 有top 和 left 两个属性 获取距离文档顶部和左侧的距离
2)基于父级的偏移 [ position() ]
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>获取元素偏移</title>
<script src="jquery.min.js"></script>
<style>
body {
padding: 0;
margin: 0;
}
.father {
position: absolute;
800px;
height: 800px;
background: pink;
padding: 50px;
margin: 50px;
}
.son {
300px;
height: 300px;
padding: 10px;
border: solid 2px red;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
console.log($('.son').offset()); // {top: 100, left: 100} //基于文档定位
console.log($('.son').position()); // {top: 50, left: 50} //基于父级定位
</script>
</body>
</html>
二 设置 或 获取 元素被卷去的头部和左侧
scrollTop() scrollLeft()
//1 不带参数是获取
//2 带参数是设置 不用写单位