画像拡大鏡の作成方法:画像拡大鏡
画像拡大鏡の作成方法を学びます。
画像拡大鏡
画像上にマウスを合わせて:

画像拡大鏡を作成する
第1ステップ - HTMLを追加:
<div class="img-magnifier-container"> <img id="myimage" src="img_girl.jpg" width="600" height="400" alt="Girl"> </div>
第2ステップ - CSSを追加:
コンテナは「相対」位置を持たなければなりません。
* {box-sizing: border-box;} .img-magnifier-container { position: relative; } .img-magnifier-glass { position: absolute; border: 3px solid #000; border-radius: 50%; cursor: none; /* 画像拡大器のサイズの設定: */ width: 100px; height: 100px; }
第3ステップ - JavaScriptの追加:
function magnify(imgID, zoom) { var img, glass, w, h, bw; img = document.getElementById(imgID); /* 放大鏡の作成: */ glass = document.createElement("DIV"); glass.setAttribute("class", "img-magnifier-glass"); /* 放大鏡の挿入: */ img.parentElement.insertBefore(glass, img); /* 放大鏡の背景属性の設定: */ glass.style.backgroundImage = "url('" + img.src + "')"; glass.style.backgroundRepeat = "no-repeat"; glass.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px"; bw = 3; w = glass.offsetWidth / 2; h = glass.offsetHeight / 2; /* ユーザーが画像上でマーカーを移動する時に実行される関数: */ glass.addEventListener("mousemove", moveMagnifier); img.addEventListener("mousemove", moveMagnifier); /* タッチパネルにも適用されます: */ glass.addEventListener("touchmove", moveMagnifier); img.addEventListener("touchmove", moveMagnifier); function moveMagnifier(e) { var pos, x, y; /* 防止在图像上移动时可能发生的任何其他操作 */ e.preventDefault(); /* 获取光标的 x 和 y 位置: */ pos = getCursorPos(e); x = pos.x; y = pos.y; /* 防止放大镜位于图像之外: */ if (x > img.width - (w / zoom)) {x = img.width - (w / zoom);} if (x < w / zoom) {x = w / zoom;} if (y > img.height - (h / zoom)) {y = img.height - (h / zoom);} if (y < h / zoom) {y = h / zoom;} /* 设置放大镜的位置: */ glass.style.left = (x - w) + "px"; glass.style.top = (y - h) + "px"; /* 显示放大镜“看到”的内容: */ glass.style.backgroundPosition = "-" + ((x * zoom) - w + bw) + "px -" + ((y * zoom) - h + bw) + "px"; } function getCursorPos(e) { var a, x = 0, y = 0; e = e || window.event; /* 获取图像的 x 和 y 位置: */ a = img.getBoundingClientRect(); /* 计算光标相对于图像的 x 和 y 坐标: */ x = e.pageX - a.left; y = e.pageY - a.top; /* 考虑任何页面滚动: */ x = x - window.pageXOffset; y = y - window.pageYOffset; return {x : x, y : y}; } }
第4歩 - 放大機能を起動する:
<script> /* 执行放大功能: */ magnify("myimage", 3); /* 画像のidとズームの強度を指定: */ </script>