问题描述:利用JavaScript知识实现鼠标在左侧照片上移动,右侧盒子内出现放大版的对应位置效果图。
详细代码:文章来源:https://www.toymoban.com/news/detail-838678.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
box-sizing: border-box;
}
.box {
width: 1250px;
height: 700px;
background-color: cadetblue;
margin: 50px auto;
padding-top: 30px;
}
.box_left {
width: 400px;
height: 400px;
border: 1px solid #666;
}
.box_left .pic_box {
width: 400px;
height: 400px;
position: relative;
}
.box_left .pic_box .pic {
width: 100%;
height: 100%;
}
.box_left .pic_box .pic img {
width: 100%;
height: 100%;
}
.box_left .pic_box .big_box {
width: 500px;
height: 500px;
overflow: hidden;
border: 1px solid #666;
position: absolute;
left: 450px;
top: 0px;
}
.box_left .pic_box .big_box img {
width: 800px;
position: absolute;
left: 0px;
top: 0px;
}
.mask {
width: 300px;
height: 300px;
background-color: bisque;
opacity: 0.7;
position: absolute;
left: 0;
top: 0px;
}
</style>
</head>
<body>
<div class="box">
<!-- 左侧放大镜 -->
<div class="box_left">
<div class="pic_box">
<div class="pic">
<img src="./5.jpg" alt="">
<div class="mask"></div>
</div>
<div class="big_box">
<img src="./5.jpg" alt="">
</div>
</div>
<!-- <ol>
<li></li>
</ol> -->
</div>
<!-- 右侧产品购买的信息 -->
<div class="box_right"></div>
</div>
<script>
var pic_box = document.querySelector('.pic_box');
var mask = document.querySelector('.mask');
var pic = document.querySelector('.pic');
var big_box = document.querySelector('.big_box');
var big_pic = document.querySelector('.big_box img');
pic.onmouseenter = function () {
mask.style.display = 'block';
big_box.style.display = 'block';
}
pic.onmouseleave = function () {
mask.style.display = 'none';
big_box.style.display = 'none';
}
pic.onmousemove=function(e){
e=e||window.event;
// 鼠标在盒子内的坐标
var x=e.pageX-pic_box.offsetLeft;
var y=e.pageY-pic_box.offsetTop;
console.log(x,y);
var maskx=pic.offsetWidth-mask.offsetWidth;
var masky=pic.offsetHeight-mask.offsetHeight;
x=x-mask.offsetWidth*0.5;
y=y-mask.offsetHeight*0.5;
if(x<=0){
x=0;
}else if(x>maskx){
x=maskx;
}
if(y<=0){
y=0;
}else if(y>=masky){
y=masky;
}
mask.style.left=x+'px';
mask.style.top=y+'px';
var picmaxX=big_box.offsetWidth-big_pic.offsetWidth;
big_pic.style.left=picmaxX*x/maskx+'px';
big_pic.style.top=picmaxX*y/masky+'px';
}
</script>
</body>
</html>
效果图: 文章来源地址https://www.toymoban.com/news/detail-838678.html
到了这里,关于JavaScript实现放大镜效果的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!