我的代码有这个大问题,我试图实现一个执行createElements函数的按钮,该按钮基本上创建了新元素(在我的情况下,它创建了输入文件),我已经成功地使它上传了不同的照片。我现在唯一的问题是css。每当用户浏览照片并将其悬停时,都应显示删除文本,以删除相应的图像。但是它没有按预期工作。请运行该代码段,您会更好地理解它。删除仅显示在第一个创建的元素上。有人可以帮忙吗?
function createElements() {
const userQuestions = document.getElementById('userQuestions');
userQuestions.insertAdjacentHTML(
'beforeend', '<center><div class="uploader" onclick="selectFile(this)"></div><input type="file" name="userprofile_picture" accept="image/*" onchange="handleImage(this)" />');
}
///code for image
function selectFile(uploader) {
uploader.nextSibling.click();
}
///Code to preview image
function handleImage(input) {
if (input.files.length) {
var reader = new FileReader();
reader.onload = function (e) {
input.previousSibling.innerHTML =
'<img width="100%" height="100%" class="image" src="' + e.target.result + '"/><div class="middle"><div class="text">Remove</div></div>';
}
reader.readAsDataURL(input.files[0]);
}
}
.uploader:hover .image {
opacity: 0.3;
}
.middle {
transition: .5s ease;
opacity: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
text-align: center;
}
.uploader:hover .middle {
opacity: 1;
}
.text {
background-color: #2196F3;
color: white;
font-size: 16px;
padding: 16px 32px;
}
<html>
<head><head>
<body>
<button onclick="createElements()">click</button>
<div id="userQuestions"></div>
</body>
</html>
请注意,不能省略createElements()
答案 0 :(得分:1)
好吧,我确实使用flex修复了CSS,建议您看看flexbox
function createElements() {
const userQuestions = document.getElementById('userQuestions');
userQuestions.insertAdjacentHTML(
'beforeend', '<center><div class="uploader" onclick="selectFile(this)"></div><input type="file" name="userprofile_picture" accept="image/*" onchange="handleImage(this)" />');
}
///code for image
function selectFile(uploader) {
uploader.nextSibling.click();
}
///Code to preview image
function handleImage(input) {
if (input.files.length) {
var reader = new FileReader();
reader.onload = function (e) {
input.previousSibling.innerHTML =
'<img width="100%" height="100%" class="image" src="' + e.target.result + '"/><div class="middle"><div class="text">Remove</div></div>';
}
reader.readAsDataURL(input.files[0]);
}
}
.uploader{
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.uploader:hover .image {
opacity: 0.3;
}
.middle {
position: absolute;
transition: .5s ease;
opacity: 0;
display: flex
}
.uploader:hover .middle {
opacity: 1;
}
.text {
margin: auto;
background-color: #2196F3;
color: white;
font-size: 16px;
padding: 16px 32px;
}
<html>
<head><head>
<body>
<button onclick="createElements()">click</button>
<div id="userQuestions"></div>
</body>
</html>