<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
</head>
<body>
<style type="text/css">
#divShow {
display:none;
}
#divInfo {
width:300px;
height:300px;
border:1px solid red;
display:none;
}
</style>
<input type="button" id="btnShow" value="展示" />
<div id="divShow">
</div>
<div id="divInfo"></div>
<script type="text/javascript">
window.onload = function () {
//得到显示div
var divShowObj = document.getElementById('divShow');
document.getElementById('btnShow').onclick = function () {
//设置为显示
divShowObj.style.display = 'block';
//位置居中
divShowObj.style.textAlign = 'center';
divShowObj.style.marginTop = '100px';
};
//数据
var data = {
"images/1.jpg": ["张三", "18", "images/11.jpg"],
"images/2.jpg": ["李四", "19", "images/21.jpg"],
"images/3.jpg": ["王五", "20", "images/31.jpg"]
}
for (var key in data) {
//根据数据创建img元素
var imgObj1 = document.createElement('img');
//src属性赋值
imgObj1.src = key;
//追加到div的子元素中
divShowObj.appendChild(imgObj1);
//设置img的高和宽
imgObj1.style.width = '150px';
imgObj1.style.height = '220px';
//设置img的间距和边框
imgObj1.style.marginRight = '20px';
imgObj1.style.border = '1px solid green';
}
//得到已经实例化完成的img对象数组
var imgObjs = document.getElementsByTagName('img');
//得到divInfo对象
var divInfoObj = document.getElementById('divInfo');
//遍历img数组
for (var i = 0; i < imgObjs.length; i++) {
imgObjs[i].onmouseenter = function () {//鼠标悬浮事件
//显示div
divInfoObj.style.display = 'block';
//创建第一个p标签
var pObj1 = document.createElement('p');
//讲名字设置到p标签的内容
pObj1.innerText = data[this.getAttribute('src')][0];
//将设置好的p标签追加到divInfo中
divInfoObj.appendChild(pObj1);
//创建第二个p标签
var pObj2 = document.createElement('p');
//将年龄设置到p标签的内容
pObj2.innerText = data[this.getAttribute('src')][1];
//添加到divInfo
divInfoObj.appendChild(pObj2);
创建第三个p标签
//var pObj3 = document.createElement('p');
//创建图片标签
var imgInfoObj = document.createElement('img');
imgInfoObj.src = data[this.getAttribute('src')][2];
//添加
//pObj3.appendChild(pObj2);
divInfoObj.appendChild(imgInfoObj);
//设置显示位置
divInfoObj.style.position = 'absolute';
divInfoObj.style.left = this.offsetLeft + 'px';
divInfoObj.style.top = this.offsetTop + this.offsetHeight +30+ 'px';
};
imgObjs[i].onmouseleave = function () {//鼠标离开事件
while (divInfoObj.hasChildNodes()) {//循环遍历移除子元素
divInfoObj.removeChild(divInfoObj.firstChild);
}
divInfoObj.style.display = 'none';
};
}
};
</script>
</body>
</html>
鼠标悬浮图片显示详细信息
最新推荐文章于 2023-11-03 10:29:29 发布