zoukankan      html  css  js  c++  java
  • HTML元素跟随鼠标一起移动,网页中回到顶部按钮的实现

    对象跟随鼠标:

    1.对象css设置绝对定位position: absolute;
    2.获取鼠标坐标;
    3.通过鼠标坐标计算出对象坐标位置,并设置为css定位的位置;

    document.onmousemove=function(event){
    		event.clientX;//鼠标X坐标
    		event.clientY;//鼠标Y坐标
    		对象.style.left=event.clientX - 对象.offsetWidth/2 + "px";
    		对象.style.top=event.clientY - 对象.offsetHeight/2 + "px";
    }
    

    回到顶部按钮(非锚点方式)

    描述:滚动条下滑一定距离会出现回到顶部按钮,顶部没有此按钮
    在这里插入图片描述
    实现方法:

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="UTF-8">
    		<title>回至顶部</title>
    		<style>
    			#totop{
    				width: 60px;
    				height: 60px;
    				position: fixed;
    				right: 20px;
    				bottom: 20px;
    				display: none;
    			}
    		</style>
    	</head>
    	<body>
    		<img src="img/top.png" id="totop"/>
    		<p>内容1</p>
    		<p>内容2</p>
    		<p>内容3</p>
    		<!--此处省略网页内容-->
    		<script>
    			var totop=document.getElementById("totop");//获取按钮img对象(div也行,只要能做成按钮)
    			var timer=null;//计时器名称
    			window.onscroll=function(){
    				var sctop=document.documentElement.scrollTop;//获取滚动条高度
    				console.log(sctop);
    				if(sctop>=200){//如果高度大于200px则显示回到顶部按钮
    					totop.style.display="block";//显示按钮
    				}else{
    					totop.style.display="none";//隐藏按钮
    				}
    			}
    			function toTop(){//回到顶部
    				document.documentElement.scrollTop-=10;
    				if(document.documentElement.scrollTop<=0){
    					clearInterval(timer);//回到顶部要清除定时器
    				}
    			}
    			totop.onclick=function(){
    				timer=setInterval(toTop,10);//点击按钮回到顶部
    			}
    		</script>
    	</body>
    </html>
    
    
  • 相关阅读:
    Codeforces 798C
    Codeforces 777E
    Codeforces 801C Voltage Keepsake(二分枚举+浮点(模板))
    【NOIP 2017】宝藏
    利普希茨
    【NOIP2008】双栈排序
    捕老鼠
    失格
    【JZOJ4307】喝喝喝
    Blocks
  • 原文地址:https://www.cnblogs.com/BIG-BOSS-ZC/p/11807344.html
Copyright © 2011-2022 走看看