用js代码做一个页面广告栏

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		*{
			margin: 0;padding: 0;
		}
		#ad{
			width: 200px;
			height: 180px;
			background-color: red;
			position: relative;
			top: 300px;
		}
		span{
			width: 20px;
			height: 108px;
			background-color: #ccc;
			display: block;
			position: absolute;
			top: 36px;
			right: -20px;
		}
	</style>
</head>
<body>
	<div id="ad">
		<span>南阳欢迎你</span>
	</div>

	<script type="text/javascript">
		window.onload=function(){
			var o=document.getElementById('ad');
			var timer;
			//鼠标经过事件
			o.onmouseover=function(){
				clearInterval(timer);
				timer=setInterval(moveRight,10);
			};

			//鼠标离开事件
			o.onmouseout=function(){
				clearInterval(timer);
				timer=setInterval(moveLeft,10);
			};

			//滑出
			function moveRight(){
				var preLeft=o.offsetLeft;
				if (preLeft>=0) {
					clearInterval(timer);//移动到边界时停止
				}else{
					o.style.left=o.offsetLeft+2+'px';//向右移动
				}
			}

			//缩回
			function moveLeft(){
				var preLeft=o.offsetLeft;
				if (preLeft<=-200){
					clearInterval(timer);
				}else{
				 	o.style.left=o.offsetLeft-2+'px';//向左移动
				}
			}
		};
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_44830974/article/details/89644848