日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

【JavaScript】- 实现图片放大镜效果

發布時間:2024/3/26 javascript 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【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】- 实现图片放大镜效果的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。