万金流
以码会友。 吾Q:578751655。 水平有限,轻喷,谢!
随笔 - 189,  文章 - 0,  评论 - 7,  阅读 - 14万

如题,js的简单使用。很多页面特效可以由此展开想象。

html:

复制代码
 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8" />
 5         <title></title>
 6         <script src="js/j1.js"></script>
 7     </head>
 8     <body onload="myinit()">
 9         <div style="width: 100px;height: 100px;border: 2px solid red;top:0;left: 0;position: relative;" id="d1">123</div>
10     </body>
11 </html>
复制代码

j1.js:

复制代码
 1 //全局变量,各个函数都要用
 2 var x;
 3 var dir_heng;
 4 var dir_shu;
 5 //初始化
 6 function myinit()
 7 {    
 8     x=document.querySelector("#d1");
 9     dir_heng=1;
10     dir_shu=1;
11     setInterval(myfloat,100);
12 }
13 function myfloat()
14 {    
15     //取左、上边距和漂浮物宽、高的数字
16     oldleft=px2num(x.style.left);
17     oldtop=px2num(x.style.top);
18     Width=px2num(x.style.width);
19     Height=px2num(x.style.height);
20     
21     //如果左边距大于窗口宽度减控件宽度 或 左边距小于0
22     //(即漂浮物向右超越边框 或 向左超越边框)
23     //则换向
24     if(oldleft>innerWidth-Width || oldleft<0)
25     {
26         dir_heng=-dir_heng;
27     }
28     //与上类似
29     if(oldtop>innerHeight-Height ||oldtop<0)
30     {
31         dir_shu=-dir_shu;
32     }
33     //获得新的左、上边距,即移动
34     newleft=oldleft+20*dir_heng+"px";
35     newtop=oldtop+20*dir_shu+"px";
36     x.style.left=newleft
37     x.style.top=newtop;
38 }
39 
40 //eg. px2num("20px"),return 20
41 function px2num(x)
42 {
43     t=parseInt(x.substring(0,x.length-2));
44     return t;
45 }
复制代码

浏览器页面上,一个红边div四处碰撞。效果自行查看。

posted on   万金流  阅读(154)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现

点击右上角即可分享
微信分享提示