<html> <head><meta charset="UTF-8"><title>Document</title><style type="text/css"> *{margin:0px; padding:0px;} .small-box {width:300px;height:300px;margin-left:100px;margin-top:100px;border:1px #ccc solid;cursor:move;float:left;position:relative; } .small-box img {width:300px;height:300px; } .tool {width:150px;height:150px;background-color:gold;opacity:0.6;filter:alpha(opacity=60);position:absolute;left:0px;top:0px;display:none; } .tool.active {display:block; } .big-box {width:300px;height:300px;border:1px #ccc solid;overflow:hidden;float:left;margin-top:100px;position:relative;display:none; } .big-box.active {display:block; } .big-box img {width:600px;height:600px;position:absolute; }</style> </head> <body><div class="small-box" id="smallBox"> <img src="img1.jpg"/> <div class="tool" id="tool"></div></div><div class="big-box" id="bigBox"> <img src="img1.jpg" id="bigImg" /></div><script> /*第一步:当页面加载完后,获取所要操作的节点对象。第二步:为smallBox添加一个鼠标浮动事件 当鼠标浮动到smallBox可视区域的时候,显示出小黄盒子tool 和右边的大盒子(小黄盒子的放大版)bigBox 添加active为smallBox添加一个鼠标离开事件 隐藏小黄盒子和右边的大盒子 去掉active第三步:为smallBox添加一个鼠标移动事件小黄盒子tool要跟着鼠标的坐标移动右边的大盒子里的图片也跟着指定的比例移动 */ var smallBox = document.getElementById("smallBox");//小盒子 var tool = document.getElementById("tool");//小盒子中的黄色区域 var bigBox = document.getElementById("bigBox");//大盒子 var bigImg = document.getElementById("bigImg");//放大的图片 //鼠标进入小盒子区域内,显示黄色区域和大盒子 smallBox.onmouseenter = function(){tool.className = "tool active";bigBox.className = "big-box active"; } //鼠标离开小盒子区域,不显示黄色区域和大盒子 smallBox.onmouseleave = function(){tool.className = "tool";bigBox.className = "big-box"; } //鼠标在小盒子内移动 smallBox.onmousemove = function(e){var _e = window.event||e;//事件对象var x = _e.clientX-this.offsetLeft-tool.offsetWidth/2;//事件对象在小盒子内的横向偏移量var y = _e.clientY-this.offsetTop-tool.offsetHeight/2;//竖向偏移量if(x<0){ x = 0;//当左偏移出小盒子时,设为0}if(y<0){ y = 0;//当上偏移出小盒子时,设为0}if(x>this.offsetWidth-tool.offsetWidth){ x = this.offsetWidth-tool.offsetWidth;//当右偏移出小盒子时,设为小盒子的宽度-黄色放大区域宽度}if(y>this.offsetHeight-tool.offsetHeight){ y = this.offsetHeight-tool.offsetHeight;//当下偏移出小盒子时,设为小盒子的高度-黄色放大区域高度}tool.style.left = x + "px";//黄色放大区域距离小盒子左偏距tool.style.top = y + "px";//黄色放大区域距离小盒子上偏距bigImg.style.left = -x*2 + "px";//放大图片移动方向相反,偏移距离加倍bigImg.style.top = -y*2 + "px"; }</script> </body></html>这里,我并没有对代码中css样式,JavaScript行为进行和html结构的分离,方便读者阅读和运行。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。