JavaScript学习笔记

使用HTML5的拖放功能实现将本地的图片的拖放到网上上

2018-04-25  本文已影响4人  小人物的秘密花园

原文地址

https://github.com/visugar/FrontEnd-examples/blob/master/08H5%E6%8B%96%E6%94%BEAPI/drag02.html

代码

HTML

<h3>将图片拖入下面内容框中</h3>
    <hr>
    <div class="img-box">
        <div class="content" id="content"></div>
        <span class="btn" id="upload" onclick="upload()">上传图片</span>
    </div>

CSS

.img-box {
    min-width: 500px;
    min-height: 500px;
}

.img-box .content {
    width: 100%;
    min-height: 450px;
    border: 1px dotted orangered;
    border-radius: 5px;
}

.img-box .btn {
    display: block;
    width: 100px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    background: orangered;
    border-radius: 3px;
    color: #fff;
    margin: 5px 0;
    font-size: 14px;
    font-family: "Microsoft YaHei";
    box-shadow: 0 0 2px orange;
    cursor: pointer;
}

JS

window.onload = function() {
    var content = document.getElementById("content");
    // 阻止document对象的默认事件
    document.ondragover = function(e) {
        e.preventDefault();
    };
    // 阻止照片在新窗口中打开
    document.ondrop = function(e) {
        e.preventDefault();
    }
    content.ondragover = function(e) {
        e.preventDefault();
    }
    content.ondrop = function(e) {
        // 获取图片路径
        var imgsFile = e.dataTransfer.files[0];
        //创建一个fileReader对象的实例
        var fs = new FileReader();
        fs.readAsDataURL(imgsFile);
        // 当图片资源加载完成后,将图片显示在content中
        fs.onload = function(e) {
            // 创建图片实例
            var img = new Image();
            img.src = fs.result;
            content.appendChild(img);
        }
    }
};

function upload() {
    var aImg = document.getElementsByTagName('img') || [];
    if (aImg.length <= 0) {
        alert('请将图片拖入内容区!')
    } else {
        for (var i = 0; i < aImg.length; i++) {
            console.log(aImg[i].getAttribute("src"));
        }
    }

}

结果

image.png
上一篇下一篇

猜你喜欢

热点阅读