HTML代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>万年历</title>
<link rel="stylesheet" type="text/css" href="css/rl.css">
<script type="text/javascript">
window.onload=function(){
var oContainer=document.getElementsByClassName('container');
// 触发器
var aBtn=document.getElementsByTagName('button');
// 被操纵对象
var oCont=oContainer.getElementsByClassName('container');
var arr=['你好啊我们一起去意大利',
'哈哈哈哈哈哈哈哈哈哈哈哈',
'llllllllllllllllllll',
'inaongd',
'555555555555555555555555555',
'666666666666',
'7777777777777777777',
'88888888888',
'99999999999',
'101010',
'111111111111111111111',
'1212121212',
];
for (var i = aBtn.length - 1; i >= 0; i--) {
aBtn[i].onmouseover=function() {
aBtn[i].index=i;
oCont.innerHTML='<h3>'+(this.index+1)+'月活动</h3><p>'+arr[this.index]+'</p>';
}
}
}
</script>
</head>
<body>
<div class="container">
<div class="wrapper">
<div class="row">
<div><button>1</button></div>
<div><button>2</button></div>
<div><button>3</button></div>
</div>
<div class="row">
<div><button>4</button></div>
<div><button>5</button></div>
<div><button>6</button></div>
</div>
<div class="row">
<div><button>7</button></div>
<div><button>8</button></div>
<div><button>9</button></div>
</div>
<div class="row">
<div><button>10</button></div>
<div><button>11</button></div>
<div><button>12</button></div>
</div>
</div>
<div class="content">
<h3>1月活动</h3>
<p>要去拜年事业有成</p>
</div>
</div>
</body>
</html>
CSS代码:
.container{
width: 190px;
margin: 0 auto;
position: relative;
}
.wrapper{
display: table;
border-collapse: separate;
border-spacing: 10px 10px;
background: #ccc;
margin:0 auto;
}
.row{
display: table-row;
}
.row div,
.row button{
display: table-cell;
height:50px;
width: 50px;
}
.row button{
font-size: 25px;
background: #333;
color: #fff;
border:none;
}
.row button:hover{
cursor: pointer;
background: #23aa11;
}
.content{
position: absolute;
left: 0;
top: 250px;
width: 190px;
display: block;
background: #ccc;
}
.content h3,
.content p{
margin: 10px;
}
.content h3{
font:bold 16px/1 '黑体';
}
.content p{
font-size: 14px;
}
报错截图:
报错信息:
Uncaught TypeError: oContainer.getElementsByClassName is not a function at window.onload
getElementsByClassName()
返回的是一个集合,而不是一个元素——注意到方法中的Elements
是加了s
的。然后你的这个逻辑我并不是很理解
这里我只能假设你是写错了,你的本意是要找
content
,那么正确的代码是上面这段代码从语法上来说是没啥大问题了,逻辑上也走得通。但是有一些假设。
在写程序的时候请注意区分
id
和class
的用法。id
用于精确表示一个节点。class
用于表示一类具有相似作用的节点。所以在通过id
和class
来查找节点的时候,也是有区别的。在你这个 HTML 中似乎更适合用id
而不是class
。同时注意
document.getElementById()
是直接找到节点而不是一个节点集合。