开发中经常遇到图片放大缩小并翻转的需求,实现方法有很多,但是写在页面里就要写个弹框来收纳,单独写一个页面,如果是vue还需要配置路由,最后想到了下面的方法,一个js方法搞定一切。
function openImg(url) {
console.log('图片地址url:', url)
let openNew = window.open(url);
let pageName = url.substring(url.lastIndexOf("/") + 1, url.length);
openNew.document.write(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${pageName}</title>
<style>
* {
margin: 0;
padding: 0;
font-size: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
width: 100vw;
min-height: 100vh;
background: #0e0e0e;
}
img {
height: 100vh;
zoom: 1;
transform: rotate(0deg);
cursor: pointer;
}
</style>
</head>
<body>
<img src="${url}" alt="" title="单击放大缩小,双击旋转图片">
<s`+ `cript>
var imgNode = document.getElementsByTagName('img')[0];
var r = 0;
imgNode.style.zoom = '1.00001'
var timeout
// 由于打开的是空白页,无法刷新,只能通过监听F5,重置参数,实现刷新的效果
window.onkeydown = function (event) {
// event.returnValue = false;//阻止默认事件,在空白页没有用
if (event.key == 'F5') {
r = 0;
imgNode.style.zoom = '1.00001'
imgNode.style.transform = 'rotate(' + r * 90 + 'deg)';
clearTimeout(timeout)
}
}
imgNode.ondblclick = function () {
imgRotate()
}
imgNode.onclick = function () {
clearTimeout(timeout)
timeout = window.setTimeout(imgZoom, 500)
}
// // 下面设置图片的宽高比例
// imgNode.onload = function (e) {
// console.log('naturalWidth:', e.path[0].naturalWidth, 'naturalHeight:', e.path[0].naturalHeight)
// let naturalWidth = e.path[0].naturalWidth
// let naturalHeight = e.path[0].naturalHeight
// if (naturalHeight > naturalWidth) {
// imgNode.style.height = '100vh';
// }
// };
function imgRotate() {
clearTimeout(timeout)
r++;
imgNode.style.transform = 'rotate(' + r * 90 + 'deg)';
}
function imgZoom() {
if (imgNode.style.zoom == '1.00001') {
imgNode.style.zoom = '1.5'
} else if (imgNode.style.zoom == '1.5') {
imgNode.style.zoom = '1'
} else if (imgNode.style.zoom == '1') {
imgNode.style.zoom = '0.5'
} else if (imgNode.style.zoom == '0.5') {
imgNode.style.zoom = '1.00001'
}
}
</s`+ `cript>
</body>
</html>`)
}