首页> 基础笔记 >JS/JQ基础学习 >经典案例 经典案例

JavaScript实例:滚动广告

作者:小萝卜 2023-03-23 浏览 276

简介JavaScript实例:滚动广告

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>滚动广告</title>
	<style type="text/css">
		*{margin:0px;padding:0px;}
		#move{width:200px;height:200px;background:orange;border-radius:50%;position:absolute;}
		#moveOne{width:200px;height:200px;background:orange;border-radius:50%;position:absolute;}
	</style>
</head>
<body>
	<div id="move"></div>
	<div id="moveOne"></div>
	<script type="text/javascript">
	//全局变量的定义
	var move = document.getElementById('move');
	var stepX = 2;//移动的步进
	var stepY = 2;
	var inte = null;

	//自动执行函数封装
	function autoRun(){
		inte = setInterval(function(){
			//获取当前元素相对父级元素的x轴的偏移量
			var x = move.offsetLeft;
			var y = move.offsetTop;

			//计算新的left值
			var newLeft = x + stepX;
			var newTop = y + stepY;

			// 计算右侧的极限位置
			var maxLeft = document.documentElement.clientWidth - move.offsetWidth;
			var maxTop = document.documentElement.clientHeight - move.offsetHeight;

			if(newLeft >= maxLeft || newLeft <= 0){//反方向移动
				stepX *= -1;
				changeColor(move);//修改背景颜色
			}

			if(newTop >= maxTop || newTop <= 0){
				stepY *= -1;
				changeColor(move);//修改背景颜色
			}

			//设置css样式
			move.style.left = newLeft + 'px';
			move.style.top = newTop + 'px';
		}, 10);
	}
	autoRun();

	//绑定鼠标移入事件
	move.onmouseover = function(){
		clearInterval(inte);
		inte = null;
	}

	//绑定鼠标离开事件
	move.onmouseout = function(){
		autoRun();
	}

	//封装颜色改变函数
	function changeColor(obj){
		var r = rand(0,255);
		var g = rand(0,255);
		var b = rand(0,255);
		obj.style.background = "rgb("+r+","+g+","+b+")";
	}

	//获取随机数
	function rand(m,n){
		return Math.ceil(Math.random()*(n-m+1))+m-1;
	}

	</script>
</body>
</html>
 

很赞哦! (0)

文章评论

    高端网站建设