效果
通过行内样式控制图片的缩放,旋转。
应用:图像预览组件
<template>
<div class="img-container">
<div v-if="imageUrl" ref="imgPreview" :class="{'image-preview':true,'image-preview-scale':isScale}">
<div class="image-wrapper">
<img ref="img" :src="imageUrl">
</div>
<div class="image-action">
<el-button icon="el-icon-search" circle @click="handleScale" />
<el-button icon="el-icon-refresh-left" circle @click="handleRotateLeft" />
<el-button icon="el-icon-refresh-right" circle @click="handleRotateRight" />
<el-button icon="el-icon-refresh" circle @click="handleReset" />
</div>
</div>
<div v-else><p>相关图片缺失</p></div>
</div>
</template>
<script>
import { prefixStyle } from '@/utils/prefixStyle'
const transformStyle = prefixStyle('transform')
// console.log(transformStyle) //webkitTransform
export default {
name: 'ImgView',
props: {
fileUrl: {
type: String,
default: ''
}
},
data() {
return {
isScale: false,
loading: false,
imageUrl: '',
rotate: 0,
scale: 1
}
},
watch: {
fileUrl() {
this.imageUrl = this.fileUrl
}
},
mounted() {
this.imageUrl = this.fileUrl
},
methods: {
handleScale() {
// 图像放大
this.isScale = true
this.scale = this.scale + 0.5
// transform兼容处理
// style html内嵌入样式
// 页面审查元素 未见 添加的前缀 但 测试了火狐 Opera 浏览器 可用
this.$refs.imgPreview.style[transformStyle] = 'scale(' + this.scale + ')'
},
handleRotateLeft() {
// 图像旋转
this.rotate = (this.rotate - 90) % 360
this.$refs.img.style[transformStyle] = 'rotate(' + this.rotate + 'deg)'
},
handleRotateRight() {
// 图像旋转
this.rotate = (this.rotate + 90) % 360
this.$refs.img.style[transformStyle] = 'rotate(' + this.rotate + 'deg)'
},
handleReset() {
// 图像重置
this.rotate = 0
this.scale = 1
this.isScale = false
this.$refs.img.style[transformStyle] = 'rotate(0deg)'
this.$refs.imgPreview.style[transformStyle] = 'scale(1)'
}
}
}
</script>
<style lang="scss" scoped>
div.img-container{
width: 100%;
height:100%;
background: #f7f7f7;
.image-preview {
box-sizing: border-box;
padding:10px;
.image-wrapper {
box-sizing: content-box;
text-align: center;
img {
width: 100%;
height: auto;
}
}
.image-action {
text-align: right;
}
}
.image-preview-scale{
position: absolute;
top:0;
left:0;
background: #f7f7f7;
z-index: 2000;
}
}
</style>
样式兼容处理:prefixStyle.js
/* jshint esversion: 6 */
export function prefixStyle(style) {
// 创建一个元素来判断当前浏览器使用的前缀
const elementStyle = document.createElement('div').style
// elementStyle 返回的是 CSSStyleDeclaration 对象
// console.log(elementStyle)
const prefix = (() => {
const transformNames = {
webkit: 'webkitTransform',
Moz: 'MozTransform',
O: 'OTransform',
ms: 'msTransform',
standard: 'transform'
}
for (const key in transformNames) {
if (elementStyle[transformNames[key]] !== undefined) {
return key
}
}
return false
})()
if (prefix === false) {
return false
}
if (prefix === 'standard') {
return style
}
// 拼接:前缀+样式首字母大写+样式剩余字符
return prefix + style.charAt(0).toUpperCase() + style.substr(1)
}