vue3 自定義圖片放大器效果的示例代碼
效果
具體代碼實現
創建商品圖片展示的vue頁面:ProductPicShow.vue
<script lang="ts" setup> import { ref, computed } from 'vue' import { useMouseInElement } from '@vueuse/core' defineProps<{ images: string[] }>() // 當前顯示的圖片索引 let active = ref(0) // ref 獲取 DOM 元素的位置 const target = ref(null) // isisOutside為 true 的時候代表鼠標未進入目標元素,為 false 時代表鼠標進入目標元素 const { elementX, elementY, isOutside } = useMouseInElement(target) // 遮罩半透明圖在商品大圖中的坐標位置 const position = computed(() => { let x = elementX.value - 100 let y = elementY.value - 100 if (x <= 0) x = 0 if (x >= 200) x = 200 if (y <= 0) y = 0 if (y >= 200) y = 200 return { x, y } }) </script> <template> <div class="product-image"> <!-- 放大鏡的大盒子 --> <div class="large" :style="[ { backgroundImage: `url(${images[active]})`, backgroundPosition: `-${position.x * 3}px -${position.y * 3}px` } ]" v-show="!isOutside" ></div> <div ref="target" class="middle"> <img :src="images[active]" alt="" /> <!-- 鼠標移動時的遮罩層 --> <div class="layer" v-show="!isOutside" :style="{ left: `${position.x}px`, top: `${position.y}px` }" ></div> </div> <ul class="small"> <li v-for="(item, index) in images" :key="item" :class="{ active: index === active }" @mouseenter="active = index" > <img :src="item" alt="" /> </li> </ul> </div> </template> <style scoped lang="less"> .product-image { width: 480px; height: 400px; position: relative; display: flex; z-index: 500; .large { position: absolute; top: 0; left: 412px; width: 600px; height: 600px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); background-repeat: no-repeat; background-size: 200% 200%; background-color: #f8f8f8; } .middle { width: 400px; height: 400px; background: #f5f5f5; position: relative; cursor: move; .layer { width: 200px; height: 200px; background: rgba(0, 0, 0, 0.2); left: 0; top: 0; position: absolute; } } .small { width: 80px; li { width: 68px; height: 68px; margin-left: 12px; margin-bottom: 15px; cursor: pointer; &:hover, &.active { border: 2px solid #27BA9B; } } } } </style>
使用:Product.vue
<template> <div class="product-info"> <div class="media"> <ProductPicShow :images="slidePics"/> </div> </div> </template> <script setup lang="ts"> import ProductPicShow from "@/views/product/components/ProductPicShow.vue" </script> <style scoped lang="less"> .product-info { min-height: 600px; background: #fff; display: flex; .media { width: 580px; height: 600px; padding: 30px 50px; } } </style>
到此這篇關於vue3 自定義圖片放大器的文章就介紹到這瞭,更多相關vue3 圖片放大器內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!