简单写的购物网站经常见的放大镜效果,可以粘贴代码看效果;
关键就是: 比例相等, 两边的比例
两边的比例两边的比例两边的比例两边的比例两边的比例两边的比例两边的比例两边的比例
<style>
.wrap{
background-color: pink;
width: 300px;
height: 300px;
position: fixed;
top: 0;
left: 0;
}
.outer {
width: 400px;
height: 400px;
background-color: green;
}
.inner {
width: 300px;
height: 300px;
background-color: pink;
}
.center {
width: 200px;
height: 200px;
background-color: yellowgreen;
}
.one {
width: 200px;
height: 200px;
position: relative;
margin: 100px;
border: 1px solid #3da5a5;
box-sizing: border-box;
background: url('./people.jpg');
background-size: 100% 100%;
float: left;
}
.tab {
width: 60px;
height: 60px;
position: absolute;
top: 0;
left: 0;
background-color: rgba(0,0,0,0.4);
cursor: move;
display: none;
}
.two {
width: 300px;
height: 300px;
border: 1px solid orange;
box-sizing: border-box;
float: right;
position: relative;
overflow: hidden;
display: none;
/* background-size: 100% 100%;
background-position: 100px 100px; */
}
.img {
position: absolute;
top: 0;
left: 0;
}
</style>
<div class="one" id="one">
<div class="tab" id="tab"></div>
</div>
<div class="two" id="two">
<img class="img" id="img" src="./people.jpg" alt="">
</div>
<script>
one.onmousemove = function(e) {
let x = e.clientX - this.offsetLeft;
let y = e.clientY - this.offsetTop;
let wid = tab.offsetWidth, heg = tab.offsetHeight;
let left = x - wid/2, top = y - heg/2;
const maxLeft = this.offsetWidth - wid;
const maxTop = this.offsetHeight - heg;
if(left <= 0) left = 0;
if(left >= maxLeft) left = maxLeft;
if(top <= 0) top = 0;
if(top >= maxTop) top = maxTop;
tab.style.left = left + 'px';
tab.style.top = top + 'px';
// right
two.style.backgroundSize = (two.offsetWidth/this.offsetWidth) * this.offsetWidth + 'px';
// console.log((two.offsetWidth/this.offsetWidth) * this.offsetWidth);
console.log(111, one.offsetWidth, tab.offsetWidth, two.offsetWidth);
img.style.width = one.offsetWidth / (tab.offsetWidth/two.offsetWidth) + 'px';
img.style.height = one.offsetHeight / (tab.offsetHeight/two.offsetHeight) + 'px';
const newleft = left / (tab.offsetWidth/two.offsetWidth) + 'px';
const newtop = top / (tab.offsetHeight/two.offsetHeight) + 'px';
img.style.left = '-' + newleft ;
img.style.top = '-' + newtop ;
}
one.onmouseenter = function(e) {
tab.style.display = 'block';
two.style.display = 'block';
}
one.onmouseleave = function(e) {
tab.style.display = 'none';
two.style.display = 'none';
}
</script>