js学习总结-拖拽、放大镜
效果图
准备大、中、小三张图片,也可以只准备像素大的一张大图(一张图代码更加简洁)
一、给三张图和遮罩一个基本的样式
<style>
.middle{
width: 400px;
height: 400px;
border:1px solid #000;
position:relative;
}
.middle>img{
width: 400px;
height: 400px;
}
.small{
width: 400px;
height: 100px;
display: flex;
justify-content: flex-start;
align-items: center;
}
.small img{
border:1px solid #0f0;
width: 50px;
height: 50px;
margin:0 5px;
}
.small img.active{
border-color:red;
}
.shade{
width: 100px;
height: 100px;
background:rgba(255,255,0,0.5);
position:absolute;
left: 0;
top: 0;
display:none;
}
.big{
width: 400px;
height: 400px;
position: absolute;
left:105%;
top: 0;
overflow:hidden;
display:none;
}
.big>img{
width: 1600px;
height: 1600px;
position:absolute;
left: 0;
top: 0;
}
.box{
margin:50px;
}
.shade:hover{
cursor:move;
}
</style>
二、js代码
<script type="text/javascript">
function Enlarge(){
// 获取元素
this.box = document.querySelector(".box");
this.middle = this.box.querySelector(".middle");
this.middleImg = this.box.querySelector(".middle>img");
this.shade = this.box.querySelector(".shade");
this.big = this.box.querySelector(".big");
this.bigImg = this.box.querySelector(".big>img");
this.smallImgs = this.box.querySelectorAll(".small>img");
var _this = this;
// 鼠标移入显示遮罩和大图
this.middle.onmouseover = ()=>{
this.over();
}
this.middle.onmouseout = ()=>{
this.out();
}
// 小图的点击事件
for(var i=0;i<this.smallImgs.length;i++){
this.smallImgs[i].onclick=function(){
_this.click(this);
}
}
}
// 小图的点击事件
Enlarge.prototype.click = function(ele){
for(var i=0;i<this.smallImgs.length;i++){
this.smallImgs[i].className = '';
}
ele.className = "active"
// 点小图换中图和大图
// 获取当前点击元素的src
// ele.getAttribute("src");
// 元素有一些属性可以直接使用 . 来操作,比如,index、src
// console.log(ele.src);
this.middleImg.src = this.bigImg.src = ele.src
}
Enlarge.prototype.over = function(){
this.shade.style.display = this.big.style.display = "block";
// 中等盒子的移动事件
this.middle.onmousemove= e=>{
// 拖拽 - 获取光标位置
var e = e || window.event;
var x = e.pageX;
var y = e.pageY;
var l = x - this.box.offsetLeft - this.shade.clientWidth/2;
if(l<=0){
l = 0;
}
if(l>=this.middle.clientWidth - this.shade.clientWidth){
l=this.middle.clientWidth - this.shade.clientWidth
}
this.shade.style.left = l + "px"
var t = y - this.box.offsetTop - this.shade.clientHeight/2;
if(t<=0){
t = 0;
}
if(t>=this.middle.clientHeight - this.shade.clientHeight){
t=this.middle.clientHeight - this.shade.clientHeight
}
this.shade.style.top = t + "px"
// 计算比例
var percentX = this.shade.offsetLeft/this.middle.clientWidth;
var percentY = this.shade.offsetTop/this.middle.clientHeight;
// 根据比例计算大图应该定位的值
var bigX = this.bigImg.clientWidth * percentX;
var bigY = this.bigImg.clientHeight * percentY;
// 将值设置给大图的定位
this.bigImg.style.left = -bigX + "px";
this.bigImg.style.top = -bigY + "px";
}
}
Enlarge.prototype.out = function(){
this.shade.style.display = this.big.style.display = "none"
}
var enlarge = new Enlarge();
</script>