今天來做一個非常常見且有意思的的案例,就是我們的滑鼠經過圖片放大的一個效果!
具體實作的效果看下面這張圖
案例分析:
黃色的遮擋層跟隨滑鼠功能,
把滑鼠坐標給遮擋層不合適,因為遮擋層坐標以父盒子為準,
首先是獲得滑鼠在盒子的坐標,
之后把數值給遮擋層做為left 和top值,
此時用到滑鼠移動事件,但是還是在小圖片盒子內移動,
發現,遮擋層位置不對,需要再減去盒子自身高度和寬度的一半,
遮擋層不能超出小圖片盒子范圍,
如果小于零,就把坐標設定為0
如果大于遮擋層最大的移動距離,就把坐標設定為最大的移動距離
遮擋層的最大移動距離:小圖片盒子寬度 減去 遮擋層盒子寬度
這種類似放大鏡的效果很多朋友肯定以為是一張圖片的放大效果,其實我們這個地方是準備了兩張圖片,滑鼠經過小圖移動大圖,這種神奇的效果就實作了,接下來我們仔細來分析一下這個效果該怎么寫代碼!
首先還是老規矩哈,在 body 里面把 html 框架搭好,引入兩張圖片,
<div class="box">
<img src="images/small.jpg" alt="" class="small">
<div class="yy"></div>
<div class="big">
<img src="images/big.jpg" alt="">
</div>
</div>
這樣寫好了我們看不出任何效果,當然需要 css 的渲染!!!
<style>
.box {
position: relative;
width: 350px;
height: 350px;
}
.yy {
position: absolute;
top: 0;
left: 0;
width: 250px;
height: 250px;
background-color: yellow;
opacity: 0.5;
border: 1px solid #333;
display: none;
}
.big {
position: absolute;
left: 360px;
top: 0px;
width: 500px;
height: 500px;
overflow: hidden;
display: none;
}
.big>img {
position: absolute;
top: 0;
left: 0;
}
</style>
為了展示效果我在隱藏之前截了個圖,基本框架搭好以后就是這個樣子啦!當然,為了更好的實作效果,這里的大圖和黃色遮擋層肯定是要隱藏的,我放在上面的代碼已經提前寫好了隱藏,

接下肯定就是用 JavaScript 來實作的頁面互動效果了,滑鼠經過隱藏,滑鼠離開顯示,以及滑鼠在小圖里面移動大圖跟著移動的效果,這樣就實作了一個放大鏡的效果!!
<script>
window.addEventListener('load', function () {
var box = document.querySelector('.box');
var yy = document.querySelector('.yy');
var big = document.querySelector('.big');
box.addEventListener('mouseover', function () {
yy.style.display = 'block';
big.style.display = 'block';
})
box.addEventListener('mouseout', function () {
yy.style.display = 'none';
big.style.display = 'none';
})
box.addEventListener('mousemove', function (e) {
var x = e.pageX - box.offsetLeft;
var y = e.pageY - box.offsetTop;
var width = x - yy.offsetWidth / 2;
var height = y - yy.offsetHeight / 2;
if (width <= 0) {
width = 0;
} else if (width >= box.offsetWidth - yy.offsetWidth) {
width = 100;
}
if (height <= 0) {
height = 0;
} else if (height >= box.offsetHeight - yy.offsetHeight) {
height = box.offsetHeight - yy.offsetHeight;
}
yy.style.left = width + 'px';
yy.style.top = height + 'px';
var bigimg = document.querySelector('.big>img');
// 大圖片的移動距離=遮擋層移動距離*大圖片最大移動距離/遮擋層最大移動距離
var bigx = width * (bigimg.offsetWidth - big.offsetWidth) / (box.offsetWidth - yy.offsetWidth);
var bigy = height * (bigimg.offsetHeight - big.offsetHeight) / (box.offsetHeight - yy.offsetHeight);
bigimg.style.left = -bigx + 'px';
bigimg.style.top = -bigy + 'px';
})
})
</script>
以上就是實作這一效果的全部代碼了,感興趣的朋友可以收藏哦,以后可就找不到這么優秀的文章了!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/355371.html
標籤:其他
上一篇:輕輕松松讓你掌握DOM的事件操作

