JS實現鼠標移入DIV隨機變換顏色

今天分享一個在 JavaScript中,實現一個鼠標移入能夠隨機變換顏色,本質就是js的隨機數運用。javascript

代碼以下:css

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			/* 這裏定義一下div(塊元素)已下span 標籤的寬.高.邊框線以及邊框線的顏色*/
			span{
				display: block;
				width: 80px;
				height: 80px;
				border: 1px solid #000000;
				float: left;
			}
		</style>
	</head>
	<body>
		<div>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
			<span></span><span></span><span></span><span></span><span></span><span></span>
		</div>
		<script type="text/javascript">
			var a=document.getElementsByTagName("span");
			/* 獲取一下span標籤 */
				for(var i=0;i<=a.length;i++){
					a[i].onmouseover=function(){
						/* 循環出每個方塊,加入鼠標移入 */
						this.style.backgroundColor="#"+Math.floor(Math.random()*16777215).toString(16);
						/* 顏色隨機顏色 */
					}
				}
		</script>
	</body>
</html>

  

效果以下:html

相關文章
相關標籤/搜索