window.onload = function () { //获取点击按钮标签 var btn = document.querySelector("button"); //获取改变倍数的input标签 var range = document.querySelector('input[type="range"]') //获取提示倍数信息的标签 var index = document.querySelector(".magIndex") //按钮点击事件函数 btn.onclick = function () { //改变放大倍数 reset(range.value) //显示放大倍数 index.innerHTML = range.value; } //获取显示的图片 var img_small = this.document.getElementsByClassName("img_small")[0]; //获取放大后的图片 var img_big = this.document.getElementsByClassName("img_big")[0]; //获取显示图片的盒子 var viewing_small = this.document.getElementsByClassName("viewing_small")[0]; //获取放大后的图片的盒子 var viewing_big = this.document.getElementsByClassName("viewing_big")[0];z //获取鼠标移动到图片上的遮罩层 var mag = this.document.getElementsByClassName("mag")[0]; //获取显示的图片的宽度 var img_smallx = img_small.clientWidth; //获取显示的图片的高度 var img_smally = img_small.clientHeight; //设定一个初始的放大倍数 var magIndex = 1; //初始放大页面 reset(magIndex) //放大镜函数 function reset(magIndex) { //设置放大后的图片宽度和高度 img_big.style.width = img_smallx * magIndex + "px"; img_big.style.height = img_smally * magIndex + "px"; //设置遮罩层的宽度和高度 mag.style.width = img_smallx / magIndex + "px"; mag.style.height = img_smally / magIndex + "px"; //设置显示的图片的盒子高度和宽度 viewing_small.style.width = img_smallx + "px"; viewing_small.style.height = img_smally + "px"; //设置大盒子的宽度和高度 viewing_big.style.width = img_smallx + "px"; viewing_big.style.height = img_smally + "px"; //当鼠标移入显示的图片的盒子时遮罩层和大图片盒子显示 viewing_small.onmouseenter = function () { mag.style.display = "block"; viewing_big.style.display = "block"; } //鼠标移出时遮罩层和大图片盒子隐藏 viewing_small.onmouseleave = function () { mag.style.display = "none"; viewing_big.style.display = "none"; } //鼠标移动事件 viewing_small.onmousemove = function (event) { //鼠标相对于屏幕的位置-小盒子相对于屏幕的位置-遮罩层的一半宽度 var x = event.clientX - viewing_small.getBoundingClientRect().left - mag.clientWidth / 2; var y = event.clientY - viewing_small.getBoundingClientRect().top - mag.clientHeight / 2; if (x < 0) { x = 0; } if (x > viewing_small.offsetWidth - mag.offsetWidth) { x = viewing_small.offsetWidth - mag.offsetWidth } if (y < 0) { y = 0; } if (y > viewing_small.offsetHeight - mag.offsetHeight) { y = viewing_small.offsetHeight - mag.offsetHeight } mag.style.left = x + "px"; mag.style.top = y + "px"; img_big.style.left = -x * magIndex + "px"; img_big.style.top = -y * magIndex + "px"; } viewing_big.onmouseenter = function () { viewing_big.style.display = "none"; } }}