zoukankan      html  css  js  c++  java
  • day25—JavaScript实现文件拖拽上传案例实践

    转行学开发,代码100天——2018-04-10

    今天记录一个利用JavaScript实现文件拖拽上传到浏览器,后天将文件打开的小案例。

    基本功能:1点击添加文件 2 文件拖拽添加

    html:

    <div id="box">
        <span id="span">选择或拖放文件</span>
        <input id="browse" type="file">
    </div>

    css:

          #box{
                position: relative;
                border:3px dashed #ddd;
                width: 200px;
                height: 70px;
                text-align: center;
                line-height: 70px;
                cursor: pointer;
            }
            #box input{
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                opacity: 0;
                cursor: pointer;
            }
            #box.hover{
                border:3px solid  #999;
            }

    javascript:

    <script type="text/javascript">
            var box = document.getElementById("box");
            var input = document.getElementById("browse");
            var span = document.getElementById("span");
            //box 事件
            box.ondragover = function()
            {
                this.className = "box hover";
    
            }
            box.ondragleave = function()
            {
                this.className = "box";
            }
    
            //input 事件
    
            input.ondragover = function(e)
            {
                e.preventDefault();
    
            }
            input.ondrop = function(e)
            {
                e.preventDefault();
                box.className = "box";
                var file = e.dataTransfer.files[0];
                show(file);
            }
            input.onchange = function()
            {
                var file = this.files[0];
                show(file);
            }
            function show(file)
            {
                span.innerHTML = file.name;
                var fr = new FileReader();
                fr.onload = function()
                {
                    var result = this.result;
                    console.log(result);
                }
                fr.readAsText(file);
            }
    
        </script>

    案例效果:

  • 相关阅读:
    测试流程之需求评审
    如何编写测试计划
    一定要知道的,那些Linux操作命令
    线上bug分析
    做一个靠谱的软件测试人员
    测试方向
    怎样才能提交一个让开发人员拍手叫好的bug单
    软件测试职业发展
    MongoDB的启动流程
    百度语音
  • 原文地址:https://www.cnblogs.com/allencxw/p/8781247.html
Copyright © 2011-2022 走看看