前端必学——实现电商图片放大镜效果(附代码)

放大镜可以说是前端人必须学会的程序之一,今天的案例为大家展示一下怎么实现放大镜的效果!

效果图展示

整个效果就是当鼠标放到展示图上的时候,会出现一个遮罩层以及弹出来一个框展示一个详情图,并且鼠标移动的时候详情图跟着移动,鼠标离开详情图消失。

HTML代码:

<html>

<head>

<style>

#small{

width: 500px;

height: 312px;

position: absolute;

left: 20px;

top: 20px;

}

#pic1{

position: absolute;

left: 0px;

top: 0px;

}

#pic1 img{

width: 100%;

height: 100%;

}

#big{

width: 200px;

height: 200px;

position: absolute;

left: 550px;

top: 50px;

border: 1px solid blue;

overflow: hidden;

}

#pic2{

width: 1000px;

height: 625px;

position: absolute;

left: 0;

top: 0;

}

#pic2 img{

width: 100%;

height: 100%;

}

#mask{

width: 100px;

height: 100px;

background: black;

opacity: 0.3;/*让遮罩层看起来透明*/

filter: alpha(opacity = 30);/*兼容不同的浏览器*/

position: absolute;

display: none;

}

</style>

<script>

window.onload = function(){//文档内容加载完之后再执行

//当鼠标移入小图片,显示遮罩层和放大的区域

$('small').onmouseenter = function(){

$('mask').style.display = 'block';

$('big').style.display='block';

}

//鼠标移出时,隐藏遮罩层和放大的区域

$('small').onmouseleave = function(){

$('mask').style.display='none';

$('big').style.display="none";

}

//鼠标移动

$('small').onmousemove = function(ev){

var e = ev || window.event;

//计算鼠标的位置,并让鼠标显示在遮罩层的中间

var l = e.clientX - $('small').offsetLeft - 50;

var t = e.clientY - $('small').offsetTop -50;

//别让遮罩层移出图片

if(l <= 0){

l = 0;

}

if(l >= 500 - 100){

l = 400;

}

if(t <= 0){

t = 0;

}

if(t >= 312 - 100){

t = 212;

}

//遮罩层的移动

$('mask').style.left = l + 'px';

$('mask').style.top = t + 'px';

//通过遮罩层移动,来计算出放大后图片的显示区域

("pic2").style.left = -("mask").offsetLeft * 2 + 'px';

("pic2").style.top = -("mask").offsetTop * 2 + 'px';

}

}

//为了更容容易的获取id

function $(id){

return document.getElementById(id);

}

</script>

</head>

<div id="small">

<div id="pic1">

<img src="mm.jpg" alt="">

</div>

<div id="mask"></div>

</div>

<div id="big">

<div id="pic2">

<img src="mm.jpg" alt="">

</div>

</div>

</html>

相关推荐
之歆17 小时前
DAY_10 JavaScript 深度解析:原型链 · 引用类型 · 内置对象 · 数组方法全攻略(下)
开发语言·前端·javascript·ecmascript
行星飞行17 小时前
从 cursor 、 Claude code 迁移到 codex,30 分钟快速上手 codex 常用技巧
前端
Pu_Nine_917 小时前
前端埋点从入门到企业实践:手写一个Demo + 主流方案对比
前端·埋点
ZC跨境爬虫18 小时前
跟着 MDN 学 HTML day_56:(HTML 表格基础完全指南)
前端·javascript·ui·html·音视频
Dxy123931021618 小时前
CSS滤镜使用方法完全指南
前端·css
AC赳赳老秦18 小时前
OpenClaw与WPS宏联动:批量执行WPS复杂操作,解决办公表格批量处理难题
java·前端·数据库·自动化·需求分析·deepseek·openclaw
Larcher18 小时前
# 告别“古法编程”:吴恩达 AI 课程学习笔记与生日贺卡项目实战
前端·github·ai编程
用户8524950718418 小时前
# 大二前端新人的AI初体验:跟着吴恩达学“Vibe Coding”,我如何用提示词“指挥”AI写代码?
前端
bupt_0118 小时前
Hermes深入理解及源码解析(二):Hermes的记忆机制
java·服务器·前端
飘尘18 小时前
WebAssembly 是什么?它为什么重要?
前端·javascript