思路:給圖片添加點擊事件,通過js獲取預覽的工具欄,在工具欄中添加自定義按鈕及事件
1、html 中 image標簽
?<el-image
? ?style="width: 139px;
? ?height: 89px"
? ?:src="fileUrl"
? ?:preview-src-list="[fileUrl]"
? ? @click="handleImageClick(fileUrl)" //添加點擊事件
/>
2、再點擊事件中,通過js操作dom,添加自定義按鈕事件
? ?handleImageClick(fileUrl) {
? ? ? this.$nextTick(() => {
? ? ? ? const viewer = document.querySelector('.el-image-viewer__wrapper') //工具欄的dom
? ? ? ? if (viewer) {
? ? ? ? ? // 防止重復添加
? ? ? ? ? if (!document.querySelector('.custom-print-btns')) {
? ? ? ? ? ? const btn = document.createElement('button') //創建按鈕
? ? ? ? ? ? btn.className = 'custom-print-btns'? //按需設計樣式
? ? ? ? ? ? btn.innerHTML = '<i class="el-icon-printer"></i>'
? ? ? ? ? ? btn.onclick = () => this.printImage(fileUrl)?//點擊按鈕觸發事件
? ? ? ? ? ? const btnGroup = viewer.querySelector('.el-image-viewer__actions__inner')
? ? ? ? ? ? if (btnGroup) {
? ? ? ? ? ? ? btnGroup.appendChild(btn) //在工具中添加按鈕
? ? ? ? ? ? }
? ? ? ? ? }
? ? ? ? }
? ? ? })
? ? },
?
3、添加后的圖
?
4、打印事件
?printImage(fileUrl) {
? ? ? const printWindow = window.open('', '_blank')
? ? ? printWindow.document.write(`
? ? ? ? <html>
? ? ? ? ? <head>
? ? ? ? ? ? <title>打印圖片</title>
? ? ? ? ? ? <style>
? ? ? ? ? ? ? body { text-align: center; margin: 0; padding: 0; }
? ? ? ? ? ? ? img { max-width: 100%; max-height: 100vh; margin: auto; }
? ? ? ? ? ? </style>
? ? ? ? ? </head>
? ? ? ? ? <body>
? ? ? ? ? ? <img src="${fileUrl}" />
? ? ? ? ? ? <script>
? ? ? ? ? ? ? window.onload = function() {
? ? ? ? ? ? ? ? setTimeout(function() {
? ? ? ? ? ? ? ? ? window.print();
? ? ? ? ? ? ? ? ? window.close();
? ? ? ? ? ? ? ? }, 200);
? ? ? ? ? ? ? }
? ? ? ? ? ? <\/script>
? ? ? ? ? </body>
? ? ? ? </html>
? ? ? `)
? ? ? printWindow.document.close()
? ? },
?
5、結果圖
?