练习11_放大镜效果.html 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <style>
  8. body{
  9. margin: 0;
  10. }
  11. .small-img{
  12. width: 400px;
  13. height: 400px;
  14. position: relative;
  15. }
  16. .small-img img{
  17. width: 100%;
  18. height: 100%;
  19. position: absolute;
  20. top:0;
  21. left: 0;
  22. }
  23. .box{
  24. width: 200px;
  25. height: 200px;
  26. background-color: #fff;
  27. position: absolute;
  28. top:0;
  29. left: 0;
  30. opacity: 0.5;
  31. }
  32. </style>
  33. </head>
  34. <body>
  35. <div class="container">
  36. <div class="small-img">
  37. <img src="./image/niu.png" alt="img">
  38. <div class="box"></div>
  39. </div>
  40. <div class="big-img"></div>
  41. </div>
  42. <script>
  43. var smallImg = document.getElementsByClassName("small-img")[0];
  44. var oBox = document.getElementsByClassName("box")[0];
  45. smallImg.onmousemove = function(e){
  46. var _top = e.clientY-100;
  47. var _left = e.clientX-100;
  48. // 控制左侧边界
  49. if(_left <= 0){
  50. _left = 0
  51. }
  52. // 控制顶部边界
  53. if(_top<=0){
  54. _top = 0;
  55. }
  56. // 控制右侧边界
  57. if(_left>=200){
  58. _left = 200;
  59. }
  60. // 控制底部
  61. if(_top>=200){
  62. _top = 200;
  63. }
  64. oBox.style.top = _top + "px";
  65. oBox.style.left = _left + "px";
  66. }
  67. </script>
  68. </body>
  69. </html>