JavaScript拖拽文件作为背景图

烁灵 posted @ 2015年6月02日 23:50 in 前端 with tags javascript , 767 阅读
<!DOCTYPE HTML>
<html>
<head>

</head>
<body>
DROP!!!!!!!!!!
<script type="text/javascript">
function chgImg(evt) {	
    var reader = evt.target;  
	console.log(reader.result);
    var file = reader.file;      
    document.getElementsByTagName("body")[0].setAttribute("style","background-image:url(" + reader.result + ");"); 
}
document.ondragstart = function(e) {
    e.preventDefault();
}
document.ondragover = function(e) {
	e.dataTransfer.dragEffect = 'copy';
    e.preventDefault();
}
document.ondrop = function(e){
	var files = e.dataTransfer.files;
	for(var i = 0, len = files.length; i < len; i++)
	{
		var f = files[i];
		if (f.type.indexOf("image") == -1) {continue;}
        var reader = new FileReader();
        reader.onloadend = chgImg;
        reader.file = f;
        reader.readAsDataURL(f);
	}
    e.preventDefault();
}

</script>
</body>
</html>

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter