วิธีสร้าง: กระจกเพื่อขยายภาพ
เรียนรู้ว่าจะสร้างกระจกเพื่อขยายภาพ
กระจกเพื่อขยายภาพ
เคลื่อนที่เมาส์เหนือภาพ:

สร้างกระจกเพื่อขยายภาพ
ขั้นที่ 1 - เพิ่ม HTML:
<div class="img-magnifier-container"> <img id="myimage" src="img_girl.jpg" width="600" height="400" alt="Girl"> </div>
ขั้นที่ 2 - เพิ่ม CSS:
容器ต้องมีการจัดตัวที่ติดตาม (relative positioning).
* {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; }
ขั้นที่สาม - เพิ่ม 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>