练习地址:http://www.fgm.cc/learn/lesson2/10.html
实现思路:用js循环创建10个div,div里面的信息用数组存储(HTML形式,因为英文是粗体,要使用strong标签)。设置它的innerHTML为对应数组元素。
onmouseenter事件触发其添加子元素img(使用onmouseover会出现闪烁问题:因为onmouseover是不断触发的)。onmouseleave事件取div的子元素,循环判断是否有一个子元素的className是photo,有即删除该节点。不使用onmouseout的原因同上。
(这次求助了大佬才写得出来…还是那句:我好菜啊!)
代码如下:
HTML
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>提示框效果</title>
<link rel="stylesheet" type="text/css" href="10_tooltip.css">
</head>
<body>
<div id="container">
<h1>各种易烊千玺形象展示-鼠标已过展现易烊千玺</h1>
<div id="show"></div>
</div>
<script type="text/javascript" src="10_tooltip.js"></script>
</body>
</html>
CSS
#container {
width: 570px;
margin: 0 auto;
border: 1px solid black;
}
h1 {
font-size: 18px;
text-align: center;
}
#show {
display: flex;
flex-wrap: wrap;
}
.infor {
width: 100px;
height: 130px;
border: 1px solid black;
margin-left: 10px;
text-align: center;
padding-top: 20px;
margin-bottom: 10px;
background: #CCCC99;
cursor: crosshair;
color: #666600;
/*opacity: 0.8;*/
}
/*这里本意是想让div变大,再塞背景图片的,但是margin等属性没办法改,所以作罢*/
/*#change {
width: 120px;
height: 150px;
margin: 0;
}*/
.photo {
width: 120px;
height: 170px;
position: relative;
left: -11px;
top: -105px;
border: 2px solid #CC6600;
}
JavaScript
window.onload = function() {
var show = document.getElementById("show");
var information = [
"<p><strong>Handsome1</strong><br>帅气</p>",
"<p><strong>Handsome2</strong><br>帅气</p>",
"<p><strong>Handsome3</strong><br>帅气</p>",
"<p><strong>Handsome4</strong><br>帅气</p>",
"<p><strong>Handsome5</strong><br>帅气</p>",
"<p><strong>Lovely1</strong><br>可爱</p>",
"<p><strong>Lovely2</strong><br>可爱</p>",
"<p><strong>Lovely3</strong><br>可爱</p>",
"<p><strong>Lovely4</strong><br>可爱</p>",
"<p><strong>Lovely5</strong><br>可爱</p>"
];
var infor = new Array();
for(var i=0; i<10; i++){
infor[i] = document.createElement("div");
show.appendChild(infor[i]);
infor[i].className = "infor";
infor[i].innerHTML = information[i];
}
for(var i=0; i<infor.length; i++){
infor[i].onmouseenter = (function(n) {
return function() {
var photo = document.createElement("img");
infor[n].appendChild(photo);
photo.src = "../../photos/"+(n+1)+".jpg";
photo.className = "photo";
}
})(i);
infor[i].onmouseleave = (function(n) {
return function(){
var childs = infor[n].childNodes;
for (var j=0; j<childs.length; j++){
if (childs[j].className == "photo"){
infor[n].removeChild(childs[j]);
break;
}
}
}
})(i);
}
};
再感慨一下:我好菜啊!