鼠標移到圖片上顯示描述信息.png
JavaScript原生代碼實現
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
img{
width:400px;
height:300px;
}
#showCountry{
position:absolute;
width:300px;
height:200px;
background-color:lightgreen;
color:black;
display:none;
border:1px solid gray;
}
</style>
<script>
var list = {
"zg": ["中國", "北京", "牡丹", "世界第二大經濟體"],
"mg": ["美國", "紐約", "玫瑰", "白人和黑人壹起勞動"],
"rb": ["日本", "東京", "櫻花", "忍者和A片"],
"hg": ["韓國", "首爾", "無窮", "女人喜歡整容的國度"]
};
window.onload = function () {
var imgs = window.document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].onmouseover = function () {
//獲取國家信息
var msg = list[this.id];
var msgStr = "國家:" + msg[0] + "<br>首都:" + msg[1] + "<br>國花:" + msg[2] + "<br>描述:" + msg[3];
var showCountry = window.document.getElementById("showCountry");
showCountry.style.display = "block";
showCountry.style.left = event.clientX + "px";
showCountry.style.top = event.clientY + "px";
showCountry.innerHTML = msgStr;
}
imgs[i].onmouseout = function () {
var showCountry = window.document.getElementById("showCountry");
showCountry.style.display = "none";
}
}
}
</script>
</head>
<body>
<div id="showCountry"></div>




</body>
</html>
jQuery實現
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="script/jquery-3.2.1.js"></script>
<script>
var list = {
"zg": ["中國", "北京", "牡丹", "世界第二大經濟體"],
"mg": ["美國", "紐約", "玫瑰", "白人和黑人壹起勞動"],
"rb": ["日本", "東京", "櫻花", "忍者和A片"],
"hg": ["韓國", "首爾", "無窮", "女人喜歡整容的國度"]
};
$(function () {
$("img").hover(function () {
var msg = list[this.id];
var countryInfo = "國家:" + msg[0] + "<br>首都:" + msg[1] + "<br>國花:" + msg[2] + "<br>描述:" + msg[3];
$("#showCountry").css({ "left": event.clientX, "top": event.clientY, "display": "block" }).html(countryInfo)
}, function () {
$("#showCountry").css("display", "none");
});
})
</script>
<style>
img {
width: 400px;
height: 300px;
}
#showCountry {
position: absolute;
width: 300px;
height: 200px;
background-color: lightgreen;
color: black;
display: none;
border: 1px solid gray;
}
</style>
</head>
<body>
<div id="showCountry"></div>




</body>
</html>