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

แสดงการขยายล่วงหน้า:
สร้างการขยายภาพ
ขั้นที่ 1 - เพิ่ม HTML:
<div class="img-zoom-container"> <img id="myimage" src="img_girl.jpg" width="300" height="240" alt="Girl"> <div id="myresult" class="img-zoom-result"></div> </div>
ขั้นที่ 2 - เพิ่ม CSS:
ตัวแทนต้องมีตำแหน่ง 'เรlatiive'。
* {box-sizing: border-box;} .img-zoom-container { position: relative; } .img-zoom-lens { position: absolute; border: 1px solid #d4d4d4; /* ตั้งขนาดของหลอด: */ width: 40px; height: 40px; } .img-zoom-result { border: 1px solid #d4d4d4; /* กำหนดขนาดของ div result: */ width: 300px; height: 300px; }
ขั้นที่สาม - เพิ่ม JavaScript:
function imageZoom(imgID, resultID) { var img, lens, result, cx, cy; img = document.getElementById(imgID); result = document.getElementById(resultID); /* สร้าง lens: */ lens = document.createElement("DIV"); lens.setAttribute("class", "img-zoom-lens"); /* ใส่ lens: */ img.parentElement.insertBefore(lens, img); /* คำนวณสัดส่วนของ result DIV และ lens: */ cx = result.offsetWidth / lens.offsetWidth; cy = result.offsetHeight / lens.offsetHeight; /* กำหนดค่าที่มีส่วนร่วมกับ result DIV: */ result.style.backgroundImage = "url('" + img.src + "')"; result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px"; /* ระบุฟังก์ชันที่จะทำงานเมื่อมีคนเคลื่อนลูกศีรษะไปยังภาพหรือเลนส์: */ lens.addEventListener("mousemove", moveLens); img.addEventListener("mousemove", moveLens); /* ใช้งานร่วมกับหน้าตั้งแบบสัมผัสด้วย: */ lens.addEventListener("touchmove", moveLens); img.addEventListener("touchmove", moveLens); function moveLens(e) { var pos, x, y; /* ป้องกันการกระทำอื่นๆ ที่อาจเกิดขึ้นเมื่อเคลื่อนย้ายภาพ: */ e.preventDefault(); /* ได้รับตำแหน่งของเครื่องหมายเลข: */ pos = getCursorPos(e); /* คำนวณตำแหน่งแกนดาวดาบ: */ x = pos.x - (lens.offsetWidth / 2); y = pos.y - (lens.offsetHeight / 2); /* ป้องกันแกนดาวดาบอยู่นอกภาพ: */ if (x > img.width - lens.offsetWidth) {x = img.width - lens.offsetWidth;} if (x < 0) {x = 0;} if (y > img.height - lens.offsetHeight) {y = img.height - lens.offsetHeight;} if (y < 0) {y = 0;} /* ตั้งตำแหน่งแกนดาวดาบ: */ lens.style.left = x + "px"; lens.style.top = y + "px"; /* แสดงภาพที่แกนดาวดาบมองเห็น: */ result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px"; } function getCursorPos(e) { var a, x = 0, y = 0; e = e || window.event; /* ได้รับตำแหน่ง x และ y ของภาพ: */ a = img.getBoundingClientRect(); /* คำนวณตำแหน่งของเครื่องหมายเลขที่สำหรับภาพ: */ 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> imageZoom("myimage", "myresult"); </script>