行业知识
前端实现图片放大缩小,图片初始化比例和容器等比宽
2026-11-13 18:49:43
来源:互联网转载
技术:vue.js element ui
✨代码
export default { data() { return { scaleValue: 100, imgCurWidth: 0, imgCurHeight: 0, imgRealWidth: 0, imgRealHeight: 0, isFirstEnter: true } }, watch: { scaleValue(val, oldVal) { const imgCurWidth = (this.imgRealWidth * val) / 100 const imgCurHeight = (this.imgRealHeight * val) / 100 this.imgCurWidth = imgCurWidth this.imgCurHeight = imgCurHeight } }, methods: { formatTooltip(val) { return val + '%' }, handleImgLoad() { let image = new Image() image.onload = () => { const imgCurWidth = image.width * (this.scaleValue / 100) const imgCurHeight = image.height * (this.scaleValue / 100) // 图片当前宽高 this.imgCurWidth = imgCurWidth this.imgCurHeight = imgCurHeight // 图片真实宽高 this.imgRealWidth = image.width this.imgRealHeight = image.height this.$nextTick(() => { let wrapperWidth = this.$refs.imgWrapper.clientWidth if (this.isFirstEnter) { this.scaleValue = Math.floor( (wrapperWidth / this.imgRealWidth) * 100 ) this.isFirstEnter = false } }) } image.src = require('../src/assets/images/testImg.jpg') } }}.img_wrapper { width: 600px; height: 600px; overflow: auto; border: 4px solid pink; position: relative; box-sizing: border-box; .scaleImg { border: 2px solid #000; box-sizing: border-box; } .elSliderStyle { width: 100px; position: absolute; top: 0; right: 40px; z-index: 99; }}