div跟随鼠标移动

tech2023-01-06  105

<!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> div { position: absolute; width: 30px; height: 30px; background-color: green; display: none; } </style> </head> <body> <div></div> <script> var d = document.querySelector('div'); document.addEventListener('mouseover', function () { d.style.display = 'block'; }); document.addEventListener('mouseout', function () { d.style.display = 'none'; }); document.addEventListener('mousemove', function (e) { // console.log(e.pageX); d.style.left = e.pageX - 15 + 'px'; d.style.top = e.pageY - 15 + 'px'; }); </script> </body> </html>

主要思想,根据鼠标的坐标改变div的left,top值

最新回复(0)