大小自适应
新进公司接了一个需求,点击文件列表可以实现预览,我就用了iframe标签,文件格式有图片还有pdf,图片大小就需要实现自适应,不然有滚动条影响观感,封装预览组件代码:
<style lang="scss">
@import './index';
</style>
<template>
<div>
<MapModal
ref="bluePrint"
name="图纸预览"
width="90%"
height="100%"
left="5%"
:showBorder="false"
class="bluePrint"
>
<div class="pdf-container">
<iframe id="iframeEle" :src="filePath" frameborder="0" style="width: 100%; height: 100%" @load="resize()"></iframe>
</div>
</MapModal>
</div>
</template>
<script>
//(mapModal是封装的一个对话框,为了统一效果)
import MapModal from '@/components/MapModal';
export default {
components: {
MapModal,
},
data() {
return {
filePath: '',
};
},
methods: {
handleOpen(src) {
this.$refs.bluePrint.isOpen = true;
this.filePath = src;
},
handleClose() {
this.$refs.bluePrint.isOpen = false;
},
//各位如果需要图片自适应的部分,只需要粘贴这个方法里面内容就可以啦
resize() {
const iframeEle = document.getElementById('iframeEle');
const idoc = iframeEle.contentWindow.document;
const img = idoc.getElementsByTagName('img')[0];
if (img) {
const curWidth = img.width;
const curHeight = img.height;
const maxWidth = iframeEle.clientWidth;
const maxHeight = iframeEle.clientHeight;
if (curWidth >= maxWidth) {
img.width = maxWidth;
const zoomTimes = curWidth / maxWidth;
img.height = curHeight / zoomTimes;
}
const curWidth1 = img.width;
const curHeight1 = img.height;
if (curHeight1 >= maxHeight) {
img.height = maxHeight;
const zoomTimes = curHeight1 / maxHeight;
img.width = curWidth1 / zoomTimes;
}
}
},
},
};
</script>
组件的使用:
使用预览组件标签
<blue-print ref="bluePrint"></blue-print>
js代码,filePreviewUrl是文件路径
this.$refs.bluePrint.handleOpen(filePreviewUrl);
居中显示
看了效果觉得图片垂直水平居中显示更好一些,所以就在上面的基础上再加几行代码
resize() {
const iframeEle = document.getElementById('iframeEle');
const idoc = iframeEle.contentWindow.document;
const img = idoc.getElementsByTagName('img')[0];
if (img) {
//居中显示就是这两行,就是用了弹性盒,清空margin、padding是因为不清空会有滚动条
const body = idoc.getElementsByTagName('body')[0];
body.setAttribute('style', 'margin:0; padding:0; display:flex; align-items:center; justify-content:center; height:100%;');
//下面是大小自适应
const curWidth = img.width;
const curHeight = img.height;
const maxWidth = iframeEle.clientWidth;
const maxHeight = iframeEle.clientHeight;
if (curWidth >= maxWidth) {
img.width = maxWidth;
const zoomTimes = curWidth / maxWidth;
img.height = curHeight / zoomTimes;
}
const curWidth1 = img.width;
const curHeight1 = img.height;
if (curHeight1 >= maxHeight) {
img.height = maxHeight;
const zoomTimes = curHeight1 / maxHeight;
img.width = curWidth1 / zoomTimes;
}
}
},