万金流
初次使用博客园,目前感觉还不错。 不知不觉用了4年零4个月了,越来越喜欢博客园。

如题,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 2023-10-25 19:52  万金流  阅读(129)  评论(0编辑  收藏  举报