vue+js实现点击图片,图片放大
1.首先在template中插入image,并赋予点击事件(这个时候是小图)
<template> <div> <img src="@/assets/images/avatar.png" @click="imgShow()" /> </div> </template>
2.data定义点击放大的图片url,imageUrl为点击后放大的大图的url
data() { return { imageUrl: require('@/assets/images/avatar.png') } },
3.定义方法
methods: { imgShow() { const image = new Image() image.src = this.imageUrl image.onload = () => { //创建弹出层 const previewContatiner = document.createElement('div') previewContatiner.style.position = 'fixed' previewContatiner.style.top = 0 previewContatiner.style.bottom = 0 previewContatiner.style.left = 0 previewContatiner.style.right = 0 previewContatiner.style.zIndex = 9999 previewContatiner.style.backgroundColor = 'rgba(0,0,0,0.8)' previewContatiner.style.display = 'flex' previewContatiner.style.justifyContent = 'center' previewContatiner.style.alignItems = 'center' document.body.appendChild(previewContatiner) //在弹出层增加图片 const previewImage = document.createElement('img') previewImage.src = this.imageUrl previewImage.style.maxWidth = '80%' previewImage.style.maxHeight = '80%' previewImage.style.zIndex = 9999 previewContatiner.appendChild(previewImage) //点击弹出层,关闭预览 previewContatiner.addEventListener('click', () => { document.body.removeChild(previewContatiner) }) } image.onerror = function () { console.log('图片加载失败') } } }