图片跟随鼠标移动事件



代码:


  1. //鼠标move事件,传入图片地址作于显示
  2. function moveImgSelector(path) {
  3. var mos = getMousePos(), wc = document.getElementById("imgdiv");
  4. with (wc.style) {
  5. left = mos.x;
  6. top = mos.y;
  7. }
  8. wc.style.display="block";
  9. document.getElementById("img").src=path;
  10. }

  11. //获取鼠标位置
  12. function getMousePos() {
  13. var e = window.event;
  14. var mouse_x = e.clientX;
  15. var mouse_y = e.clientY;
  16. var scroll_x = window.pageXOffset || document.body.scrollLeft;
  17. var scroll_y = window.pageYOffset || document.body.scrollTop;
  18. var win_width = document.body.offsetWidth;
  19. var win_height = document.body.offsetHeight;
  20. var image_width = 400;
  21. var image_height = 400;
  22. if(mouse_x < 2){
  23. move_to_x = scroll_x + 2;
  24. }else if(mouse_x > win_width - image_width - 20){
  25. move_to_x = scroll_x + mouse_x - image_width - 20;
  26. }else{
  27. move_to_x = scroll_x + mouse_x;
  28. }
  29. if(mouse_y < 2){
  30. move_to_y = scroll_y + 2;
  31. }else if(mouse_y > win_height - image_height - 20){
  32. move_to_y = scroll_y + mouse_y - image_height - 20;
  33. } else {
  34. move_to_y = scroll_y + mouse_y;
  35. }
  36. return {x:move_to_x , y :move_to_y}
  37. }
  38. //离开事件,清除悬浮的imgdiv
  39. function cleanImgDiv(){
  40. document.getElementById("imgdiv").style.display="none";
  41. }

原文地址:https://www.cnblogs.com/signheart/p/6598134.html