放大镜.html 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. *{
  10. margin: 0;
  11. padding: 0;
  12. }
  13. #container{
  14. position: relative;
  15. }
  16. #smallBox{
  17. width: 400px;
  18. height: 400px;
  19. }
  20. #bigBox{
  21. width: 800px;
  22. height: 800px;
  23. left: 400px;
  24. top: 0;
  25. position: absolute;
  26. }
  27. #drag{
  28. width: 200px;
  29. height: 200px;
  30. background: rgba(0,0,0,0.3);
  31. position: absolute;
  32. left: 0;
  33. top: 0;
  34. display: none;
  35. }
  36. </style>
  37. </head>
  38. <body>
  39. <div id="container">
  40. <div id="smallBox">
  41. <img src="images/1.jpg" alt="">
  42. <div id="drag"></div>
  43. </div>
  44. <div id="bigBox">
  45. <img src="images/2.jpg" alt="">
  46. </div>
  47. </div>
  48. <script>
  49. var small = document.getElementById('smallBox')
  50. var drag = document.getElementById('drag')
  51. //鼠标划入显示遮罩层
  52. small.onmouseover = function(){
  53. drag.style.display = 'block'
  54. }
  55. //鼠标划出显示遮罩层
  56. small.onmouseout = function(){
  57. drag.style.display = 'none'
  58. }
  59. //鼠标滑动
  60. small.onmousemove = function(e){
  61. var xLeft = e.clientX - drag.offsetWidth / 2
  62. var xTop = e.clientY - drag.offsetHeight /2
  63. drag.style.left = xLeft + 'px'
  64. drag.style.top = xTop + 'px'
  65. if(drag.offsetLeft <= 0){
  66. drag.style.left = 0
  67. }
  68. if(drag.offsetTop <= 0 ){
  69. drag.style.top = 0
  70. }
  71. //横轴最大移动距离
  72. var zLeft = small.offsetWidth - drag.offsetWidth
  73. //纵轴最大移动距离
  74. var zTop = small.offsetHeight - drag.offsetHeight
  75. if(drag.offsetLeft > zLeft){
  76. drag.style.left = zLeft + 'px'
  77. }
  78. if(drag.offsetTop > zTop){
  79. drag.style.top = zTop + 'px'
  80. }
  81. }
  82. </script>
  83. </body>
  84. </html>