1、通过事件实时获取鼠标当前对于窗体的相对位置,代码如下
<script>
document.onmousemove = mouseMove;
var posx;
var posy;
function mouseMove(event)
{
var e = event || window.event;
var scrollx = document.documentElement.scrollLeft || document.body.scrollTop;
var scrolly= document.documentElement.scrollTop || document.body.scrollTop;
posx = e.pageX || e.clientX + scrollx;
posy = e.pageY || e.clientY + scrolly;
// console.log(x);
// console.log(y);
}
</script>
2、对需要自定义显示Title的控件设置mouseover以及mouseleave事件函数,以下是为了展现效果写的函数,ShowTitle中的内容可自行修改都是针对css的设置,通过js获取控件然后通过innertext设置自定义Title中的文字内容。
function ShowTitle() {
var Title = document.getElementById("title");
var str ="测试悬停弹框asdasdsadsadsasadsasadasd"
Title.style.display = "block";
Title.style.top = posy+'px';
Title.style.left = posx+'px';
Title.style.position = "absolute";
Title.style.zIndex=9999;
Title.style.border="solid black 1px";
Title.style.backgroundColor = "white";
Title.style.width="auto";
Title.innerText=str;
}
function HiddTitle(){
document.getElementById("title").style.display="none";
}
完整代码如下(图片自行替换):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
.centerClass
{
position: absolute;
top: 50%;
left: 50%;
}
</style>
</head>
<body>
<div style="position: absolute;z-index:999;background-color: antiquewhite;">
<img src="img/posicon.png" title="测试" onmouseover="ShowTitle()"
onmouseleave="HiddTitle()">
</div>
<div id="title" style="display: none;"></div>
<script>
document.onmousemove = mouseMove;
var posx;
var posy;
function mouseMove(event)
{
var e = event || window.event;
var scrollx = document.documentElement.scrollLeft || document.body.scrollTop;
var scrolly= document.documentElement.scrollTop || document.body.scrollTop;
posx = e.pageX || e.clientX + scrollx;
posy = e.pageY || e.clientY + scrolly;
// console.log(x);
// console.log(y);
}
function ShowTitle() {
var Title = document.getElementById("title");
var str ="测试悬停弹框asdasdsadsadsasadsasadasd"
Title.style.display = "block";
Title.style.top = posy+'px';
Title.style.left = posx+'px';
Title.style.position = "absolute";
Title.style.zIndex=9999;
Title.style.border="solid black 1px";
Title.style.backgroundColor = "white";
Title.style.width="auto";
Title.innerText=str;
}
function HiddTitle(){
document.getElementById("title").style.display="none";
}
</script>
</body>
</html>
注意把握控件的宽和高,会影响鼠标实时去位置和onmouseover ,onmouseleave事件的触发。这里用了div包裹img未设置img宽高所以实际触发会以外部div为准。
鼠标进入前效果图:
鼠标进入后效果图: