js#offset和 scroll家族

js中有一套方便的获取元素尺寸的办法,就是 offset家族,offset家族包括:

  1. offsetWidth
  2. offsetHight
  3. offsetLeft
  4. offsetTop
  5. 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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值