js的代码:
核心属性
offsetWidth:offsetWidth 属性是一个只读属性,它返回该元素的像素宽度
使用clientHeight和clientWidth属性返回元素的可见高度和宽度,
值得注意的是我这里用了document.documentElement.clientHeight来获取body的高度
原因是: 在HTML 中, body 是整个DOM 的根, 而在XHTML 中, document 才是根, body 不再是根, 所以取body 的属性时, 不能再取到整个页面的值.
<script>//设置初始图片的坐标var x = 0;var y = 0;//每次移动的距离var vx = 1;var vy = 1;function fun(){var box = document.getElementById("box");box.style.top = y+"px";box.style.left = x+"px";x = x+vx;y = y+vy;//如果x+图片宽度大于窗口宽度或者x<0,反方向移动 if((x+box.offsetWidth)>document.body.clientWidth||x<0){vx = -vx;}if((y+box.offsetHeight)>document.documentElement.clientHeight||y<0){vy = -vy;}}setInterval("fun()",1);</script>
HTML代码:
<div id="box" style="width:300px;height:300px; position: absolute"><img style="width:300px;height:300px" src="img/花.jpg"/><marquee width="100%" behavior="alternate"scrolldelay="60"><span style="color:red;font-size:20px"><b>加油</b></span></marquee></div><div id="box2" style="width:300px;height:300px; position: absolute"><img style="width:300px;height:300px" src="img/靓女.jpg"/><marquee width="100%" behavior="alternate"scrolldelay="60"><span style="color:red;font-size:20px"><b>奥力给</b></span></marquee></div>