我们可以从本地的资源中拖拽一张图片到网页中,这在HTML和JS的结合下是比较简单的。也即是说一张图片不仅可以在网页中进行拖动,还可以从电脑上拖动。具体实现如下:
(1)HTML中代码实现如下:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title></title>
- <style>
- #imgContainer{
- background-color: aqua;
- width: 500px;
- height: 500px;
- }
- </style>
- <script src="app02.js"></script>
- </head>
- <body>
- <div id="imgContainer"></div>
- <div id="msg"></div>
- </body>
- </html>
(2)JS中实现如下:
- /**
- * Created by chenyufeng on 15/9/28.
- */
- var imgContainer,msgDiv;
- window.onload = function(){
- imgContainer = document.getElementById("imgContainer");
- msgDiv = document.getElementById("msg");
- imgContainer.ondragover = function(e){
- e.preventDefault();
- };
- imgContainer.ondrop = function(e){
- e.preventDefault();
- //showObj(e.dataTransfer.files);
- var f = e.dataTransfer.files[0];
- var fileReader = new FileReader();
- fileReader.onload = function(e){
- showObj(e.target);
- imgContainer.innerHTML = "<img src=\""+fileReader.result+"\">"
- };
- fileReader.readAsDataURL(f);
- }
- };
- function showObj(obj){
- var s = "";
- for(var k in obj){
- s+=k+":"+obj[k]+"<br/>"
- }
- msgDiv.innerHTML = s;
- }