HTML5 拖拽图片到网页内
来源:互联网 发布:爱丽小屋淘宝旗舰店 编辑:程序博客网 时间:2024/04/28 09:52
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>拖拽本地图片到页面指定元素内</title>
<script type="text/javascript"> window.onload = function() {/*拖拽事件监听========================================*/ var oDropBox = document.getElementById('dropBox'); oDropBox.addEventListener('dragover', function(e) { e.stopPropagation(); e.preventDefault(); }, false); oDropBox.addEventListener('drop', handleDrop, false); function handleDrop(e) { e.stopPropagation(); e.preventDefault(); var fileList = e.dataTransfer.files, //获取拖拽文件 fileType = fileList[0].type, oImg = document.createElement('img'), reader = new FileReader(); if (fileType.indexOf('image') == -1) { alert('请拖拽图片~'); return; } reader.onload = function(e) { oImg.src = reader.result; oDropBox.innerHTML = ''; oDropBox.appendChild(oImg); } reader.readAsDataURL(fileList[0]) }/*控制大小==========================================*/document.getElementById("btnLarger").onclick = function(){var obj = document.getElementById("dropBox");if(!obj || obj.width >= 800 || obj.height >= 800){return;}increaseObjWidth(obj,10);increaseObjHeight(obj,10);}document.getElementById("btnSmaller").onclick = function(){var obj = document.getElementById("dropBox");if(!obj || obj.width <= 0 || obj.height <= 0){return;}increaseObjWidth(obj,-10);increaseObjHeight(obj,-10);}//=============================================== }function increaseObjWidth(obj,increaseBy){obj.style.width = parseInt(obj.style.width) + increaseBy + "px";}function increaseObjHeight(obj,increaseBy){obj.style.height = parseInt(obj.style.height) + increaseBy + "px";} </script>
</head><body><div><input type="button" value="+" id ="btnLarger"></input><input type="button" value="-" id="btnSmaller"></input></div> <div id="dropBox" style="float:left;width:300px;height:200px;margin:10px 0 0 0;border:1px solid #015EAC;color:#666;overflow:hidden;"> </div></body></html>