<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>鼠标移入移出事件</title> <style> * { margin: 0; padding: 0; } div { margin: 100px; width: 300px; height: 300px; background-color: rgb(70, 124, 150); color: white; font-size: 14px; position: relative; } p { background-color: rgb(238, 161, 130); width: 100px; height: 30px; line-height: 30px; text-align: center; position: absolute; /* 让光标事件不起作用,解决光标闪烁问题 */ pointer-events: none; } </style> </head> <body> <div> <p>我是提示信息</p> </div> <script> //获取div的dom节点 var divEle = document.querySelector('div') var pEle = document.querySelector('p') //获取元素p的尺寸 divEle.onmousemove = function (e) { //获取事件对象 e = e || window.event //获取光标位置,并把p元素的光标点设置成中心 var x = e.offsetX - pEle.offsetWidth / 2 var y = e.offsetY - pEle.offsetHeight / 2 //边界判断 //左边界 if (x < 0) { x = 0 } //右边界 if (x > divEle.offsetWidth - pEle.offsetWidth) { x = divEle.offsetWidth - pEle.offsetWidth } // 上边界 if (y < 0) { y = 0 } // 下边界 if (y > divEle.offsetHeight - pEle.offsetHeight) { y = divEle.offsetHeight - pEle.offsetHeight } pEle.style.top = y + 'px' pEle.style.left = x + 'px' } //鼠标移入出现 divEle.onmouseover = function() { pEle.style.display = 'block' } //鼠标移出隐藏 divEle.onmouseout = function() { pEle.style.display = 'none' } </script> </body> </html>