(编辑:jimmy 日期: 2024/11/13 浏览:2)
实现功能: 将桌面图片拖入指定地方,生成相框和相关信息。
相框需要自己配置,设置为背景,在CSS中设置。
效果如图:
html部分:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" type="text/css" href="test3.css"/> <script type="text/javascript" src="test3.js"></script> </head> <body> <h1 style="text-align: center;">H5拖放API之图片相框效果</h1> <hr /> <div class="box"></> 请将图片拖放至此处 </div> <div class="box2"></div> </body> </html>
CSS部分:
* { margin: 0px; padding: 0px; } .box2 hr { border: 3px solid blueviolet; } .box { width: 240px; height: 150px; border: 1px dotted red; text-align: center; margin: 20px auto; line-height: 150px; } .box2 { margin: 20px auto; width: 240px; padding: 30px; border: 3px solid pink ; font-size: 13px; } .photoFrame { border-top: 15px solid #90EE90; border-bottom: 15px solid #90EE90; border-left: 15px solid #48D1CC; border-right: 15px solid #20B2AA; border-style: inset; width: 200px; height: 200px; background: url(../imgs/ptoto.jpg); margin: 10px auto; position: relative; overflow: hidden; } img { position: absolute; width: 154px; height: 141px; left: 25px; top: 30px; right: 30px; bottom: 30px; } li { list-style-type: none; }
JS部分
window.onload = function() { var box2 = document.querySelector(".box2"); var box = document.querySelector(".box"); var count = 0; function photoFrame() { var d1 = document.createElement("div"); d1.className = "photoFrame"; d1.style.marginTop = "30px"; d1.style.marginLeft = "5px"; var img = document.createElement("img"); img.src = ""; count++; img.id = 'img' + parseInt(count); d1.appendChild(img); return d1; } box.ondragover = function(ev) { ev.preventDefault(); } box.ondrop = function(ev) { ev.preventDefault(); var files = ev.dataTransfer.files; //获取当前文件的最新修改日期 var lastModified = files[0].lastModifiedDate; //修改当前文件的最新修改日期的描述格式 var lastModifiedStr = lastModified ? lastModified.toLocaleDateString() + ' ' + lastModified.toLocaleTimeString() : 'n/a'; //设置图片下方状态信息栏描述内容 var fileStatus = "<li>1.名称:" + files[0].name + "<br>2.类型:" + files[0].type + "<br>3.大小:" + files[0].size + "字节" + "<br>4.修改时间:" + lastModifiedStr + "</li>" + "<hr/>"; box2.appendChild(photoFrame()); box2.innerHTML = box2.innerHTML + fileStatus; //设置图片路径 function setPath() { var fd = new FileReader(); if(files[0].type.indexOf('image') != 1) { fd.readAsDataURL(files[0]); count++; var id = "img" + parseInt(count - 1); var img = document.getElementById(id); fd.onload = function() { var img = document.getElementById(id); img.src = this.result; } } } setPath(); } }
总结