元素偏移量offset
1.可以动态获取元素的位置、大小
2.获得元素距离带有定位的父元素的位置
3.获得自身元素的宽度、高度
注意:返回值不带px单位
常见offset属性
offset系列属性 |
作用 |
element.offsetParent |
返回作为该元素带有定位的父元素,如果父级元素都没有定位,则返回body |
element.offsetTop |
返回元素相对父级元素的上方偏移量/距离 |
element.offsetLeft |
返回元素相对父级元素的左侧偏移量/距离 |
element.offsetWidth |
返回自身的宽度、包含padding、边框、内容的宽度,返回值不带px单位 |
element.offsetHeight |
返回自身的高度、包含padding、边框、内容的宽度,返回值不带px单位 |
offset与style的区别
offset的特点 |
style的特点 |
offset可以得到任何样式的样式值 |
style只能得到行内样式的样式值 |
offset是只读属性 |
style是可读可写属性 |
offsetWidth返回值不带单位px的字符串 |
style.width返回值带单位px的字符串 |
offsetWidth包含padding、边框、内容宽度 |
style.width不包含padding、边框、内容宽度 |
只获取位置、大小用offset |
需要给元素改值,用style |
常见offset系列属性的作用
获取鼠标在盒子的坐标-案例
<html >
<head>
<title>demo1</title>
<style>
div{
width: 300px;
height: 300px;
background-color: pink;
margin: 50px 100px;
}
</style>
</head>
<body>
<div>
</div>
<script>
var div = document.querySelector('div');
div.addEventListener("mousemove",function(e){
var PageX = e.pageX;
var PageY = e.pageY;
var X = div.offsetLeft;
var Y = div.offsetTop;
div.innerText = "x坐标:"+ (PageX-X) + " y坐标:"+ (PageY-Y);
});
</script>
</body>
</html>
拖拽框-案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>demo2</title>
<style>
h1{
width: 500px;
margin: 10px auto;
text-align: center;
cursor:pointer;
}
.form{
display: none;
position:absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 500px;
height: 200px;
border: 1px solid #eee;
text-align:center;
box-shadow: 0px 0px 20px #ddd;
z-index: 9;
background-color: #fff;
}
.form div{
height: 40px;
line-height: 40px;
}
.form button{
width: 100px;
height: 50px;
border: 1px solid #eee;
background-color: #fff;
}
.closeBtn{
display: block;
width: 50px;
height: 50px;
line-height: 50px;
font-size: 16px;
border: 1px solid #eee;
border-radius: 50%;
position: absolute;
top: -25px;
right: -25px;
background-color: #fff;
cursor:pointer;
}
.bg{
display: none;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-color:rgba(0,0,0,.3);
}
.title{
cursor: move;
}
</style>
</head>
<body>
<h1>点击,弹出登录框</h1>
<div class="form">
<span class="closeBtn">关闭</span>
<div class="title">登录会员
</div>
<div class="user">用户名:<input type="text" id="username"></div>