當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
【JavaScript】- 实现图片放大镜效果
生活随笔
收集整理的這篇文章主要介紹了
【JavaScript】- 实现图片放大镜效果
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這里實現 鼠標移入顯示一個放大鏡 的效果,就好比商品看著太小,鼠標移動則會顯示一個框出來,框里面就是鼠標移動商品的放大鏡
下面上代碼:
html結構:
<div class="box"><div class="child"></div></div><div class="minBox"><img src="./f78c3274055b21915d496adb9ed874d5.gif" alt=""></div>css樣式:
.box {width: 400px;height: 400px;background: url('./f78c3274055b21915d496adb9ed874d5.gif') no-repeat center/cover;margin: 100px 20px;border: 1px solid black;position: relative;box-sizing: border-box;}.child {width: 200px;height: 200px;background-color: rgba(0, 0, 0, 0.1);position: absolute;left: 0;top: 0;}.minBox {width: 500px;height: 500px;background-color: rgba(0, 0, 0, 0.5);position: absolute;left: 500px;top: 100px;display: none;overflow: hidden;}.minBox img {width: 300%; /* 這里可以根據自己圖片要求添加 */position: absolute;left: 0;top: 0;}js:?
?
// 獲取元素let box = document.querySelector('.box') // 父容器let child = document.querySelector('.child') // 子容器let minBox = document.querySelector('.minBox') // 放大鏡容器let minBoxImg = document.querySelector('.minBox img') // 大圖片// 遮擋層最大移動距離const parentWidth = box.offsetWidth - child.offsetWidthconst parentHeight = box.offsetHeight - child.offsetHeightbox.addEventListener('mousemove', function (e) {let x = e.clientX - box.offsetLeftlet y = e.clientY - box.offsetToplet width = x - child.offsetWidth / 2let height = y - child.offsetHeight / 2// 限制遮擋層x軸最大最小邊界,不超出父容器if (width <= 0) {width = 0} else if (width >= parentWidth) {width = parentWidth}// 限制遮擋層y軸最大最小邊界,不超出父容器if (height <= 0) {height = 0} else if (height >= parentHeight) {height = parentHeight}// 鼠標移動的位置賦值給遮擋層child.style.top = height + 'px'child.style.left = width + 'px'// 大圖片的移動距離 = 遮擋層移動距離 * 大圖片最大移動距離 / 遮擋層最大移動距離minBoxImg.style.left = -(width * (minBoxImg.offsetWidth - minBox.offsetWidth) / (box.offsetWidth - child.offsetWidth)) + 'px'minBoxImg.style.top = -(height * (minBoxImg.offsetHeight - minBox.offsetHeight) / (box.offsetHeight - child.offsetHeight)) + 'px'// 移入父容器顯示放大鏡minBox.style.display = 'block'})// 移除父容器隱藏放大鏡box.addEventListener('mouseleave', function () {minBox.style.display = 'none'})總結
以上是生活随笔為你收集整理的【JavaScript】- 实现图片放大镜效果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Revit API 之 动态修改Ribb
- 下一篇: 【学习笔记33】JavaScript延时