JavaScript制作网页动画

在这里插入图片描述

代码如下

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>window对象</title>
		<script type="text/javascript">
			//定义几个全局变量
			var w;//页面的宽度
			var img;//图像对象
			var imgLeft;//图像左边的位置
			var imgWidth;//图像的宽度
			var delta=5;//每次移动的距离
			window.onload=function(){
				//对四个变量赋初值
				w=window.innerWidth;
				img=document.getElementById("img");
				imgLeft=img.offsetLeft;
				imgWidth=img.width;
				//调用move()方法,改变图片位置
				move();
			};
			function move(){
				//判断图像是否越界(超出页面的宽度)
				if(imgLeft<0||imgLeft+imgWidth>w){
					delta=-delta;//变号
				}
				img.style.left=imgLeft+delta+"px";
				//移动位置后,需要重新修改左边的位置
				imgLeft=img.offsetLeft;
				//重复不断的调用次函数
				setTimeout(move,5);
			}
		</script>
		<style type="text/css">
			#img{
				position: absolute;
				left: 0;
				top: 50%;
			}
		</style>
	</head>
	<body>
			<img src="img/img6.jpg" id="img"  />
		</div>
		
	</body>
</html>

素材:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/liyunfu233/article/details/83615153