javascript - 使用上传按钮上传图片

标签 javascript jquery html css

我有一个上传按钮,允许用户只上传一张图片,它会显示在一个 div 中。 上传图片后,如果用户点击图片,我想在弹出窗口中显示图片。请帮助我如何实现这一目标。

最佳答案

试试这段代码

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#blah').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

$("#imgInp").change(function() {
  readURL(this);
});

var modal = document.getElementById('myModal');
$("#blah").click(function() {
  modal.style.display = "block";
  $('.img').html(this);
});

var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
  modal.style.display = "none";
}
/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}


/* Modal Content/Box */

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 50%;
  /* Could be more or less, depending on screen size */
}


/* The Close Button */

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
  <input type='file' id="imgInp" />
  <img id="blah" src="#" alt="your image" height="100" width="100" />
</form>

<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <div class="img"></div>
  </div>

</div>

关于javascript - 使用上传按钮上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50987289/

相关文章:

java - ajax GET请求Spring的403禁止错误

javascript - Angular 2 - ngfor - 带空格的字段

javascript - 通过引用传递给函数的对象数量

JavaScript 文件加载顺序和依赖管理

javascript - 从价格中去除美元符号

javascript - JS 输入按键事件 - 无法读取 null 的属性 'addEventListener'

jquery - 这是在 Angular JS 项目中使用 jQuery 的好习惯吗?

javascript - 在 3 列中显示 div

javascript - 如何使用外部js文件访问表单?如何从客户端隐藏js的敏感内容?

jquery - 访问 iframe 父级中的 div