使用JavaScript生成可编辑能够插入图片的网页表格
时间: 2024-03-24 18:41:45 浏览: 71
可以使用以下代码生成可编辑的带图片的表格:
```html
<!DOCTYPE html>
<html>
<head>
<title>Editable Table with Image Upload</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 5px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
td img {
max-width: 100%;
max-height: 100%;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<h1>Editable Table with Image Upload</h1>
<table id="editable-table">
<thead>
<tr>
<th>Name</th>
<th>Image</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td contenteditable="true">Product 1</td>
<td>
<img id="image-preview" src="" alt="No Image" class="hidden">
<input id="image-upload" type="file" accept="image/*">
</td>
<td>
<button id="image-upload-btn">Upload</button>
</td>
</tr>
<tr>
<td contenteditable="true">Product 2</td>
<td>
<img id="image-preview-2" src="" alt="No Image" class="hidden">
<input id="image-upload-2" type="file" accept="image/*">
</td>
<td>
<button id="image-upload-btn-2">Upload</button>
</td>
</tr>
</tbody>
</table>
<script>
const imageUploadBtn = document.querySelector('#image-upload-btn');
const imageUpload = document.querySelector('#image-upload');
const imagePreview = document.querySelector('#image-preview');
const imageUploadBtn2 = document.querySelector('#image-upload-btn-2');
const imageUpload2 = document.querySelector('#image-upload-2');
const imagePreview2 = document.querySelector('#image-preview-2');
imageUpload.addEventListener('change', function() {
const file = this.files[0];
const reader = new FileReader();
reader.addEventListener('load', function() {
imagePreview.src = reader.result;
imagePreview.classList.remove('hidden');
});
if (file) {
reader.readAsDataURL(file);
}
});
imageUploadBtn.addEventListener('click', function() {
imageUpload.click();
});
imageUpload2.addEventListener('change', function() {
const file = this.files[0];
const reader = new FileReader();
reader.addEventListener('load', function() {
imagePreview2.src = reader.result;
imagePreview2.classList.remove('hidden');
});
if (file) {
reader.readAsDataURL(file);
}
});
imageUploadBtn2.addEventListener('click', function() {
imageUpload2.click();
});
</script>
</body>
</html>
```
该代码会生成一个带有两行可编辑的表格,每行包含一个可编辑的文本单元格和一个包含图片上传按钮和预览图像的单元格。当用户选择图像并上传时,JavaScript代码将在预览单元格中显示图像。您可以根据需要添加更多行或自定义样式。
阅读全文