js中有一套方便的获取元素尺寸的办法,就是 offset家族,offset家族包括:
- offsetWidth
- offsetHight
- offsetLeft
- offsetTop
- offsetParent
<style>
#p{
width:300px;
height: 300px;
margin: 10px;
padding: 10px;
background: greenyellow;
}
</style>
<body>
<div id='p'>
</div>
<script type="text/javascript">
var p = document.querySelector('#p');
</script>
</body>
offsetWidth = content + padding+border
offsetLeft: 父元素边框 + 父元素内边距+ 父元素外边距 注意:
返回距离上级盒子(带有定位)左边的位置;如果父级都没有定位,则以浏览器为准
### scrollTop的写法
网页被卷去的 头部和左边部分 , scrollTop 和 scrollLeft
scrollTop这个属性的写法要注意兼容性
window.pageYoffset||
document.body.scrollTop||document.documentElement.scrollTop
页面滚动的 函数有 scrollTo 和 scrollBy两个
scrollTo 是绝对的, scrollBy是相对于自己的位置滚动,回到顶部的动画 可以使用 scrollTo来实现
回到顶部的特效实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
body{
height: 6000px;
}
#p{
height: 100px;
background-color: black;
width: 100vw;
}
#ad{
height: 300px;
text-align: center;
border: 1px solid bisque;
}
#fly{
position: fixed;
right: 100px;
bottom: 100px;
width: 100px;
height: 60px;
}
</style>
<body>
<div id='ad'>
我是广告
</div>
<div id='p'>
nav
</div>
<script type="text/javascript">
var p = document.querySelector('#p');
window.onscroll = function(e) {
// console.log(123)
if(window.pageYOffset>300) {
p.style.position = 'fixed';
p.style.top = 0;
p.style.left = 0;
}else{
p.style.position = 'static';
p.style.top = 0;
p.style.left = 0;
}
}
</script>
<button id='fly'>
fly
</button>
<script type="text/javascript">
var fly = document.querySelector('#fly');
var step = 10;
fly.onclick=function() {
let y = window.pageYOffset;
var it = setInterval(function() {
y = y-step;
step +=2;
if(y<=0) {
y = 0;
clearInterval(it)
}
scrollTo(0,y);
});
}
</script>
</body>
</html>