<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 500px;
margin: 300px auto;
border: solid 1px black;
position: relative;
}
.content h2 {
background-color: #ccc;
padding: 10px 0;
border: 1px solid #000;
margin-bottom: 30px;
}
.sign p {
width: 200px;
background: #eee;
margin: 0;
display: none;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div class="box">
<div class="content">
<h3>這是標題一</h3>
<h3>這是標題二</h3>
</div>
<div class="sign">
<p>第一個內容</p>
<p>第二個內容</p>
</div>
</div>
</body>
<script src='js/jquery.js'></script>
<script>
var aH =$(".content h3");
var aP =$(".sign p");
或者(原生的寫法)
var aH=document.querySelectorAll(".title h2");
var aP=document.querySelectorAll(".cont p");
for (var i = 0; i < aH.length; i++) {//先遍歷元素
aH[i].index = i; //編號
aH[i].onmouseover = function () {//移進來顯示
aP[this.index].style.display = "block";
}
aH[i].onmouseout = function () {//移出去消失
aP[this.index].style.display = "none"
}
aH[i].onmousemove = function (eve) { //使p跟着鼠標走
var e = eve || window.event
aP[this.index].style.left = e.offsetX + 5 + "px";
aP[this.index].style.top = e.offsetY + 5 + this.offsetTop + "px";
//由於p的定位相對於大框,offset的座標相對於事件源,不夠,須要加上事件源相對於大框的left和top;+5是爲了讓p和h錯開,這樣p就不會一直閃爍了。
}
}
</script>
</html>
用jq實現:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 500px;
margin: 300px auto;
border: solid 1px black;
position: relative;
}
.content h2 {
background-color: #ccc;
padding: 10px 0;
border: 1px solid #000;
margin-bottom: 30px;
}
.sign p {
width: 200px;
background: #eee;
margin: 0;
display: none;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div class="box">
<div class="content">
<h3 data-con='名稱:aa;體重:168'>這是標題一</h3>
<h3 data-con='名稱:bb;體重:58'>這是標題二</h3>
</div>
<div class="sign">
<p></p>
</div>
</div>
</body>
<script src='js/jquery.js'></script>
<script>
var aH =$(".content h3");
var aP =$(".sign p");
for (var i = 0; i < aH.length; i++) {//先遍歷元素
aH[i].index = i; //編號
aH[i].onmouseover = function () {//移進來顯示
var dataC=$(this).attr('data-con')
console.log(dataC)
aP.show()
aP.html(dataC)
}
aH[i].onmouseout = function () {//移出去消失
aP.hide()
}
aH[i].onmousemove = function (eve) { //使p跟着鼠標走
var e = eve || window.event
aP.css("left",e.offsetX + 5 + "px").css("top",e.offsetY + 5 + this.offsetTop + "px")
// 由於p的定位相對於大框,offset的座標相對於事件源,不夠,須要加上事件源相對於大框的left和top;+5是爲了讓p和h錯開,這樣p就不會一直閃爍了。
}
}
</script>
</html>複製代碼