js图片随鼠标移动案例

    技术2022-07-10  121

    js图片随鼠标移动案例

    <!-- 案例分析 1、鼠标不断的移动,使用鼠标移动事件:mousemove 2、在页面中移动,给document注册事件 3、图片要移动距离,而且不占位置,使用绝对定位 4、核心原理:每次鼠标移动,我们都会获得最新的鼠标坐标,把这个x和y坐标作为图片的top和left值就可以移动图片 --> <style> img{ width: 60px; position: absolute; transform: translate(-50% , -50%); /*将图片移到鼠标中心点*/ } </style> <img src="img/leimu.png" alt=""> <script> var pic = document.querySelector('img'); document.addEventListener('mousemove', function(e){ // mousemove 只要鼠标移动1px 就会触发这个事件 var x = e.pageX; var y = e.pageY; console.log('x:' + x, 'y:' + y); pic.style.left = x + 'px'; pic.style.top = y + 'px'; }) </script>
    Processed: 0.014, SQL: 9