Alan Hou的个人博客

JS实现放大镜效果

电商网站中会经常出现图片的放大效果,在产品页面尤为常见,如淘宝、京东、一号店等网站都会采用悬浮鼠标在右侧出现图片放大效果。
要实现这种效果可能过JS或jQuery等代码来实现,示例效果如下(通过将鼠标悬浮在下面的图片上进行查看):

首先通过getElementById或其它方法来获取各个对象,然后通过onmouseover和onmouseout事件来显示和隐藏放大镜和右侧图片,示例代码如下:

objMark.onmouseover = function(){
objFloatBox.style.display = "block";
objBigBox.style.display = "block";
}

objMark.onmouseout = function(){
objFloatBox.style.display = “none”;
objBigBox.style.display = “none”;
}

核心代码为onmousemove事件

objMark.onmouseover = function(){

objFloatBox.style.display = “block”;
objBigBox.style.display = “block”;
}

objMark.onmouseout = function(){

objFloatBox.style.display = “none”;
objBigBox.style.display = “none”;
}

objMark.onmousemove =function(ev){
var _event = ev || window.event;//使用window.event解决IE兼容问题

var left = _event.clientX – objDemo.offsetLeft – objMark.offsetLeft – objFloatBox.offsetWidth/2;
var top = _event.clientY – objDemo.offsetTop – objMark.offsetTop – objFloatBox.offsetHeight/2;
//解决放大镜框脱离出左侧小图片的问题
if(left <0){ left = 0; }else if(left > (objMark.offsetWidth – objFloatBox.offsetWidth)){
left = objMark.offsetWidth – objFloatBox.offsetWidth;
}
if(top < 0){ top = 0; }else if(top > (objMark.offsetHeight – objFloatBox.offsetHeight)){
top = objMark.offsetHeight – objFloatBox.offsetHeight;
}
//鼠标移动获取放大镜悬浮框的位置
objFloatBox.style.left = left+ “px”;
objFloatBox.style.top = top + “px”;
//计算大图片显示相对小图片的放大比例
var percentX = left / (objMark.offsetWidth – objFloatBox.offsetWidth);
var percentY = top / (objMark.offsetHeight – objFloatBox.offsetHeight);
//鼠标移动获取右侧大图片的位置
objBigBoxImage.style.left = -percentX * (objBigBoxImage.offsetWidth – objBigBox.offsetWidth) + “px”;
objBigBoxImage.style.top = -percentY * (objBigBoxImage.offsetHeight – objBigBox.offsetHeight) + “px”;
}

退出移动版