JS放大镜(适用于任何像素比)
HTML:
<div style="display:flex;">
<div id="box1">
<div id="box0"></div>
</div>
<div id="box2">
<div id="box3">
</div>
</div>
</div>
CSS:
<style>
* {
margin: 0;
padding: 0;
}
#box0 {
position: absolute;
background-color: rgba(0, 0, 0, .3);
z-index: 1;
}
#box1 {
position: relative;
width: 640px;
height: 452px;
background: url(0.jpg) no-repeat;
background-size: 100%;
overflow: hidden;
}
#box2 {
width: 640px;
height: 452px;
overflow: hidden;
}
#box3 {
width: 3200px;
height: 2260px;
background: url(0.jpg) no-repeat;
background-size: 3200px 2260px;
}
</style>
JS:
<script>
let box0 = document.getElementById('box0')//放大镜
let box1 = document.getElementById('box1')//缩略图
let box2 = document.getElementById('box2')//原图框
let box3 = document.getElementById('box3')//原图
let sizeWidth = getStyleNum(getStyle(box3, "width")) / getStyleNum(getStyle(box1, "width"))//原图与缩略图的宽度比
let sizeHeight = getStyleNum(getStyle(box3, "height")) / getStyleNum(getStyle(box1, "height"))//原图与缩略图的高度比
window.onload = function () {
box0.style.width = getStyleNum(getStyle(box1, "width")) / sizeWidth + 'px';
box0.style.height = getStyleNum(getStyle(box1, "height")) / sizeHeight + 'px'
}
box1.onmousemove = function (ev) {
let _event = ev || window.event
let left = _event.pageX - box1.offsetLeft
let top = _event.pageY - box1.offsetTop
let minleft = _event.pageX - box1.offsetLeft//放大镜离左侧的最小距离
let minTop = _event.pageY - box1.offsetTop//放大镜离上方的最小距离
let maxleft = box1.offsetWidth - box0.offsetWidth / 2//放大镜离左侧的最大距离
let maxTop = box1.offsetHeight - box0.offsetHeight / 2//放大镜离上方的最大距离
left = left < 0 ? 0 : left;
top = top < 0 ? 0 : top;
if (left <= maxleft && minleft > box0.offsetWidth / 2) {
box0.style.left = (left - box0.offsetWidth / 2) < 0 ? 0 : (left - box0.offsetWidth / 2) + 'px';
box3.style.backgroundPositionX = -sizeWidth * left + sizeWidth * box0.offsetWidth / 2 + 'px';
}
if (top <= maxTop && minTop > box0.offsetHeight / 2) {
box0.style.top = (top - box0.offsetHeight / 2) < 0 ? 0 : (top - box0.offsetHeight / 2) + 'px';
box3.style.backgroundPositionY = -sizeHeight * top + sizeHeight * box0.offsetHeight / 2 + 'px';
}
let leftEnd = (-sizeWidth * left + left) < 0 ? (-sizeWidth * left + left) : (-left + sizeWidth * left)
let topEnd = (-sizeHeight * top + top) < 0 ? (-sizeHeight * top + top) : (-top + sizeHeight * top)
}
//获取dom节点生效的样式值
function getStyle(obj, arr) {
if (window.getComputedStyle) {
return window.getComputedStyle(obj, null)[arr]
}
return ele.currentStyle[arr]
}
//将生效的样式值转为Number
function getStyleNum(Str) {
let ret = Str.split('px')
return ret[0] - 0
}
</script>