如何在点击div元素后上传HTML中的图像

  • 本文关键字:HTML 图像 元素 div html
  • 更新时间 :
  • 英文 :


我知道有<input type="file"/>,但我在<div>中有一个<img>,我很想请用户在点击该<div>后上传图像。这是我的代码:

<div class="container">
<img src="..." alt="Profile image" class="profileImg">
<div class="overlay">
<i class="fas fa-pencil-alt text"></i>
</div>
</div>

这只在HTML中可能吗?还是我需要JS或其他东西?

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
.uploader {
opacity: 0;
position: absolute;
z-index: 1;
left: 0;
top: 0;
}
.container {
position: relative
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<img src="..." alt="Profile image" id='image' class="profileImg">
<input type='file' class='uploader' onchange="readURL(this);" />
<div class="overlay">
<i class="fas fa-pencil-alt text"></i>
</div>
</div>

您可以参考上面的代码。我点击图片添加src并显示

如果我没看错,你想点击一张图片来启动打开文件对话框,或者在手机上提示用户拍照。你只想在HTML中使用它,你可以尝试一下,但是,它有一点内联CSS。

干杯,Martin

<label for='image'>
<img src='image/source.png'>
<input type='file' id='image' style='display:none;' name='image'>
</label>

文件输入的自定义样式可能很棘手,但这里有一篇关于codrops的有用文章。

基本上,您希望使用<label>元素以语义上可访问的方式对<input type="file">进行样式化和自定义。

HTML:

<input type="file" name="file" id="file" class="inputfile" />
<!-- The magic that makes it work -->
<label for="file">Choose a file</label>

CSS:

/* Hiding the default input */
.inputfile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
/* Styling the new label */
.inputfile + label {
font-size: 1.25em;
font-weight: 700;
color: white;
background-color: black;
display: inline-block;
padding: 40px;
}
.inputfile:focus + label,
.inputfile + label:hover {
background-color: red;
}
/* Accessibility */
.inputfile + label {
cursor: pointer; /* "hand" cursor */
}
/* Keyboard Navigation */
.inputfile:focus + label {
outline: 1px dotted #000;
outline: -webkit-focus-ring-color auto 5px;
}

最新更新