效果

上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
/* 默认样式 */
/* *{
margin: 0;
padding: 0%;
} */
/* 商品图片框 */
.shop{
/* 改一下 */
/* float:right; */
display: flex;
position: relative;
/* relative影响浮动 */
width: 300px;
height: 300px;
border: 1px solid yellow;
background-image: url(../图片1/1.webp);
background-size: 100% 100%;
/* x,y占比;不满图片重复平铺 */
margin-right: 200px;
}
/* 滑块 */
.slider{
position: absolute;
width: 150px;
height: 150px;
background-color: red;
opacity: .5;
/* opacity,元素不透明度,即透明度设置 */
display: none;
}
.mirror{
float: left;
position: relative;
overflow: hidden;
width: 400px;
height: 400px;
border: 1px solid red;
/* 隐藏 */
display: none;
}
img{
width: 800px;
height: 800px;
/* */
position: relative;
}
</style>
<body>
<div class="shop">
<div class="slider"></div>
</div>
<div class="mirror">
<img src="../图片1/1.webp" alt="">
</div>
</body>
<script>
// 故意不加;
let dShop=document.querySelector(".shop")
let dSlider=document.querySelector(".slider")
let dMirror=document.querySelector(".mirror")
// 用this写法呢 let img=this..
// 不知道
let img=document.querySelector("img");
// 方法1,当鼠标移入dshop触发事件,dslider和dmirror为true
// dSlider.style.display="false";
// dMirror.style.display="false";
// 没这么写这回事
dShop.onmouseenter=function(){
dSlider.style.display="block";
dMirror.style.display="block";
// .style.display="block"显示
}
// 2.function 鼠标移出dshop时,dslider和dmirror隐藏
dShop.onmouseleave=function(){
dSlider.style.display="none";
dMirror.style.display="none";
}
//3. dslider要随鼠标移动 dSlider与img等比例移动
dShop.onmousemove=function(e){
// 用到了this
let x=e.clientX - this.offsetLeft - 75;
let y=e.clientY -this.offsetLeft -75;
//取75是 slider的一半,为了是鼠标在slider居中
// let y=e.clienty - e.offsetTop -75;
// 那这里的thi指的是什么呢
// 边界处理,150根据slider
x=(x<0)?0:x;
x=(x>150)?150:x;
y=(y<0)?0:y;
y=(y>150)?150:y;
dSlider.style.left=x+'px';
dSlider.style.top=y+'px';
let l1=dSlider.offsetLeft;
//到这茫茫然
let t1=dSlider.offsetTop;
let w1=300;
let w2=800;
// 想起来了,这些数据是slider在shop里的移动
let l2=l1*w2/w1*-1;
let t2=t1*w2/w1*-1;
img.style.left=l2+'px';
img.style.top=t2+'px';
// 那么关于放大比例呢
}
</script>
</html>
本文介绍了一种基于HTML、CSS和JavaScript的商品图片放大镜效果的实现方式。通过使用简单的前端技术,当鼠标悬停在商品缩略图上时,会显示一个放大的图像预览,并随着鼠标的移动而移动,提供更好的用户体验。


被折叠的 条评论
为什么被折叠?



