Vue3實現圖片放大鏡效果
更新時間:2021年08月18日 14:55:44 作者:WQ佩奇大哥
這篇文章主要為大家詳細介紹了Vue3實現圖片放大鏡效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Vue3實現圖片放大鏡效果的具體代碼,供大家參考,具體內容如下
實現效果

代碼
<template>
<div class="goods-image">
<!-- 大圖容器 -->
<div
class="large"
:style="[
{
backgroundImage: `url(${imageList[curId]})`,
backgroundPositionX: position.backgroundPositionX,
backgroundPositionY: position.backgroundPositionY,
},
]"
v-if="isShow"
></div>
<div class="middle" ref="target">
<img :src="imageList[curId]" alt="" />
<!-- 蒙層容器 -->
<div class="layer" :style="{ left: left + 'px', top: top + 'px' }" v-if="isShow"></div>
</div>
<ul class="small">
<li
v-for="(img, i) in imageList"
:key="i"
@mouseenter="curId = i"
:class="{ active: curId === i }"
>
<img :src="img" alt="" />
</li>
</ul>
</div>
</template>
<script>
import { reactive, ref, watch } from 'vue'
import { useMouseInElement } from '@vueuse/core'
export default {
name: 'GoodsImage',
props: {
imageList: {
type: Array,
default: () => {
return []
}
}
},
setup () {
const curId = ref(0)
const target = ref(null)
// elementX: 鼠標距離左側的偏移值
// elementY:表表距離頂部的偏移值
// isOutside: 是否在容器外部 外部true 內部 false
const { elementX, elementY, isOutside } = useMouseInElement(target)
const left = ref(0) // 滑塊距離左側的距離
const top = ref(0) // 滑塊距離頂部的距離
const isShow = ref(false) // 顯示大圖和蒙層圖的顯示和隱藏
const position = reactive({ // 大圖顯示的位置,默認是0
backgroundPositionX: 0,
backgroundPositionY: 0
})
watch(
// 監(jiān)聽的對象
[elementX, elementY, isOutside],
() => {
if (elementX.value < 100) {
// 左側最小距離
left.value = 0
}
if (elementX.value > 300) {
left.value = 200
}
if (elementX.value > 100 && elementX.value < 300) {
left.value = elementX.value - 100
}
if (elementY.value < 100) {
// 左側最小距離
top.value = 0
}
if (elementY.value > 300) {
top.value = 200
}
if (elementY.value > 100 && elementY.value < 300) {
top.value = elementY.value - 100
}
// 控制背景圖移動
// 1. 蒙層移動的方向和大圖背景移動的方向是相反的
// 2. 蒙層和大圖由于面積大小是1:2的 蒙層每移動一個像素 大圖移動倆個像素
// backgrondPosition:x,y;
position.backgroundPositionX = -left.value * 2 + 'px'
position.backgroundPositionY = -top.value * 2 + 'px'
// 當isOutside的值發(fā)生變化的時候,立刻取反賦值給isShow
// isOutside: 是否在容器外部 外部true 內部 false
isShow.value = !isOutside.value
},
{}
)
return {
curId,
target,
left,
top,
position,
isShow
}
}
}
</script>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關文章
在Vue?3中使用OpenLayers加載GPX數據并顯示圖形效果
本文介紹了如何在Vue 3中使用OpenLayers加載GPX格式的數據并在地圖上顯示圖形,通過使用OpenLayers的GPX解析器,我們能夠輕松地處理和展示來自GPS設備的地理數據,需要的朋友可以參考下2024-12-12
手把手搭建安裝基于windows的Vue.js運行環(huán)境
手把手教大家搭建安裝基于windows的Vue.js的運行環(huán)境,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
element-resize-detector監(jiān)聽普通元素的實現示例
當涉及到網頁元素的實時尺寸變化監(jiān)測時,element-resize-detector?是一個值得推薦的開源庫,本文主要介紹了element-resize-detector監(jiān)聽普通元素的實現示例,感興趣的可以了解一下2024-07-07

