分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

原生js实现一个DIV的碰撞反弹运动

发布时间:2023-09-06 02:01责任编辑:沈小雨关键词:js

 原生js实现一个DIV的碰撞反弹运动:

  关键在于DIV的边界检测,进而改变运动方向,即可实现碰撞反弹效果。

<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Title</title> ???<style> ???????*{margin:0;} ???????div{height:100px;width:100px;background:red;position:absolute;} ???????/*添加绝对定位*/ ???</style> ???<script> ???????window.onload=function(){ ???????????var btn=document.getElementById("btn"); ???????????var div=document.getElementById("div"); ???????????var speedx=6; ???????????var speedy=8; ???????????var t=null; ???????????btn.onclick=function(){ ???????????????clearInterval(t); ???????????????t=setInterval(function(){ ???????????????????var l=div.offsetLeft+speedx; ???????????????????var t=div.offsetTop+speedy; ???????????????????if(l>=document.documentElement.clientWidth-div.offsetWidth){ ???????????????????????speedx*=-1; ???????????????????????l=document.documentElement.clientWidth-div.offsetWidth; ???????????????????}else if(l<=0){ ???????????????????????speedx*=-1; ???????????????????????l=0; ???????????????????} ???????????????????if(t>=document.documentElement.clientHeight-div.offsetHeight){ ???????????????????????speedy*=-1; ???????????????????????t=document.documentElement.clientHeight-div.offsetHeight; ???????????????????}else if(t<=0){ ???????????????????????speedy*=-1; ???????????????????????t=0; ???????????????????} ???????????????????div.style.left=l+"px"; ???????????????????div.style.top=t+"px"; ???????????????},10); ???????????} ???????} ???</script></head><body><input type="button" id="btn" value="开始运动"><div id="div"></div></body></html>

原生js实现一个DIV的碰撞反弹运动

原文地址:https://www.cnblogs.com/mycognos/p/9240515.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved