function previewImage(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { var img = document.createElement("img"); img.src = e.target.result; img.alt = "照片"; img.onclick = function () { showPopup(img.src); }; // 隐藏原始的input元素 input.style.display = "none"; // 添加图片到input元素的父节点 input.parentNode.appendChild(img); }; reader.readAsDataURL(input.files[0]); } } function showPopup(imageSrc) { var popup = document.createElement("div"); var popupImg = document.createElement("img"); var scale = 1; var isDragging = false; var startX, startY, translateX, translateY;
时间: 2024-04-15 16:28:01 浏览: 108
预览图片功能
这段代码是用来预览和放大图片的。`previewImage` 函数用于选择图片文件后预览它,并将其添加到对应的输入框之外。`showPopup` 函数用于在单击预览图片时显示一个弹出窗口,并允许对图片进行缩放和拖动操作。
下面是完整的代码示例:
```javascript
function previewImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("img");
img.src = e.target.result;
img.alt = "照片";
img.onclick = function () {
showPopup(img.src);
};
// 隐藏原始的 input 元素
input.style.display = "none";
// 添加图片到 input 元素的父节点
input.parentNode.appendChild(img);
};
reader.readAsDataURL(input.files[0]);
}
}
function showPopup(imageSrc) {
var popup = document.createElement("div");
var popupImg = document.createElement("img");
var scale = 1;
var isDragging = false;
var startX, startY, translateX, translateY;
popup.className = "popup";
popup.onclick = function () {
document.body.removeChild(popup);
};
popupImg.src = imageSrc;
popupImg.className = "popup-image";
popupImg.onmousedown = function (e) {
isDragging = true;
startX = e.clientX;
startY = e.clientY;
translateX = 0;
translateY = 0;
};
popupImg.onmousemove = function (e) {
if (isDragging) {
var deltaX = e.clientX - startX;
var deltaY = e.clientY - startY;
translateX += deltaX;
translateY += deltaY;
startX = e.clientX;
startY = e.clientY;
popupImg.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
}
};
popupImg.onmouseup = function () {
isDragging = false;
};
popupImg.onwheel = function (e) {
e.preventDefault();
var delta = Math.max(-1, Math.min(1, e.deltaY));
scale += delta * 0.1;
scale = Math.max(0.1, scale);
popupImg.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
};
popup.appendChild(popupImg);
document.body.appendChild(popup);
}
```
请确保在 HTML 文件中正确引入相关的 CSS 样式,这样弹出窗口和图片的显示效果才能正常展示。
希望这个解答对你有帮助!如果你还有其他问题,请随时提问。
阅读全文