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>

    案例效果:

  • 相关阅读:
    node.js 笔记一
    mysql 错误2203 1061 及安装最后出现2003现象的解决办法
    git shell 命令大全
    Mysql常用命令行大全
    php 魔术方法 说明
    php linux 环境搭建
    Linux下源码编译安装MySQL 5.5.8
    linux 压缩解压缩命令
    ftp 命令全集
    sublime text2
  • 原文地址:https://www.cnblogs.com/allencxw/p/8781247.html
Copyright © 2011-2022 走看看