<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>cv图片</title>
<style>
#past-contener {
border: 1px solid #1d8eff;
border-radius: 20px;
min-height: 100px;
padding: 15px;
}
#reset-up {
height: 50px;
width: 100%;
margin-top: 10px;
border-radius: 20px;
background-color: #1d8eff;
color: #ffffff;
border: none;
box-shadow: 0px 7px 8px #cfcece;
}
</style>
</head>
<body>
<div contenteditable="true" id="past-contener" onfocus="onFocus()" oninput="onInput(event)">粘在这里</div>
<button id="reset-up" onclick="resetUp(true)">重新上传</button>
<script>
const imageInt = document.querySelector("#past-contener");
const resetBtn = document.querySelector("#reset-up");
showResetBtn("none") // 隐藏【重新上传】摁钮
// 监听粘贴框的粘贴事件
imageInt.addEventListener("paste", function(e) {
let file = null;
const items = (e.clipboardData || window.clipboardData).items;
if (items && items.length) {
for (var i = 0; i < items.length; i++) {
if (items[i].type.includes("image")) {
file = items[i].getAsFile();
break;
}
}
};
if (file) {
console.log("文件:", file);
showResetBtn("block");
setTimeout(() => {
resetUp(false)
})
// 此时获取到file文件对象,即可处理上传相关逻辑
}
});
// 重新上传
function resetUp(bl) {
imageInt.setAttribute('contenteditable', bl);
if (bl) {
onFocus();
imageInt.focus();
showResetBtn("none");
}
};
// 【重新上传】摁钮显示控制
function showResetBtn(value) {
resetBtn.style.display = value;
};
// 对焦清空内容
function onFocus() {
imageInt.innerHTML = "";
};
// 监听输入
function onInput(event) {
if (!event.target.innerHTML.includes("<img src=")) {
onFocus();
alert("请粘贴图片")
}
}
</script>
</body>
</html>
js 前端实现复制粘贴图片到输入框上传
于 2024-09-06 21:16:04 首次发布