溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

HTML5制作圖片拖拽上傳預(yù)覽組件

發(fā)布時間:2020-05-09 10:08:07 來源:億速云 閱讀:542 作者:Leah 欄目:web開發(fā)

本文詳細介紹HTML5實現(xiàn)圖片拖拽上傳預(yù)覽組件具體操作,配合代碼使用效果更佳,非常適合初學者入門,感興趣的小伙伴們可以參考一下。

H5中拖拽事件有:
[ - ] DragDrop:拖放完成,也就是鼠標拖入對象并在拖放區(qū)域釋放。
[ - ] DragEnter :拖放進入,也就是鼠標拖放對象進入拖放區(qū)域。
[ - ] DragLeave:離開拖放區(qū)域。
[ - ] DragOver :拖放對象懸浮于拖放區(qū)域,在拖放區(qū)域內(nèi)移動時多次觸發(fā)。

1.拖拽文件獲取文件信息

示例

<!DOCTYPE html><html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .example {                padding: 10px;                border: 1px solid #ccc;
            }            
            #drop_zone {                border: 2px dashed #bbb;                -moz-border-radius: 5px;                -webkit-border-radius: 5px;                border-radius: 5px;                padding: 25px;                text-align: center;                font: 20pt bold 'Vollkorn';                color: #bbb;
            }        </style>
    </head>
    <body>
        <div class="example">
            <div id="drop_zone">將文件拖放到此處</div>
            <output id="list"></output>
        </div>
        <script>
            function handleFileSelect(evt) {
                evt.stopPropagation(); //阻止默認事件
                evt.preventDefault(); //阻止默認事件
                var files = evt.dataTransfer.files;//獲取文件集
                var output = [];                for(var i = 0, f; f = files[i]; i++) {
                    output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
                        f.size, ' bytes, last modified: ',
                        f.lastModifiedDate.toLocaleDateString(), '</li>');
                }                document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
            }            function handleDragOver(evt) {
                evt.stopPropagation();
                evt.preventDefault();
                evt.dataTransfer.dropEffect = 'copy';
            }            var dropZone = document.getElementById('drop_zone');
            dropZone.addEventListener('dragover', handleDragOver, false);
            dropZone.addEventListener('drop', handleFileSelect, false);            //body中阻止 拖拽事件防止拖拽錯誤
            document.body.addEventListener('dragover', function(evt) {
                evt.stopPropagation(); //阻止默認事件
                evt.preventDefault(); //阻止默認事件
                return false;
            }, false);            document.body.addEventListener('drop', function(evt) {
                evt.stopPropagation(); //阻止默認事件
                evt.preventDefault(); //阻止默認事件
                return false; 
            }, false);        </script>
    </body> </html>

2.限制文件大小與文件格式

<!DOCTYPE html><html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .example {                padding: 10px;                border: 1px solid #ccc;
            }            
            #drop_zone {                border: 2px dashed #bbb;                -moz-border-radius: 5px;                -webkit-border-radius: 5px;                border-radius: 5px;                padding: 25px;                text-align: center;                font: 20pt bold 'Vollkorn';                color: #bbb;
            }        </style>
    </head>
    <body>
        <div class="example">
            <div id="drop_zone">將文件拖放到此處</div>
            <output id="list"></output>
        </div>
        <script>
            function handleFileSelect(evt) {
                evt.stopPropagation(); //阻止默認事件
                evt.preventDefault(); //阻止默認事件
                var files = evt.dataTransfer.files;//獲取文件集
                var output = [];                for(var i = 0, f; f = files[i]; i++) {                      if(f.size<1024*1024*2&&(f.type=="image/png"||f.type=="image/jpeg")){//<===這里
                            output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
                            f.size, ' bytes, last modified: ',
                            f.lastModifiedDate.toLocaleDateString(), '</li>');
                    }
                }                document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
            }            function handleDragOver(evt) {
                evt.stopPropagation();
                evt.preventDefault();
                evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
            }            var dropZone = document.getElementById('drop_zone');
            dropZone.addEventListener('dragover', handleDragOver, false);
            dropZone.addEventListener('drop', handleFileSelect, false);            //body中阻止 拖拽事件防止拖拽錯誤
            document.body.addEventListener('dragover', function(evt) {
                evt.stopPropagation(); //阻止默認事件
                evt.preventDefault(); //阻止默認事件
                return false;
            }, false);            document.body.addEventListener('drop', function(evt) {
                evt.stopPropagation(); //阻止默認事件
                evt.preventDefault(); //阻止默認事件
                return false; 
            }, false);        </script>
    </body> </html>

3.顯示縮略圖與動態(tài)增刪效果

示例

<!doctype html><html>
    <head>
        <meta charset="UTF-8" />
        <title>簡易上傳預(yù)覽</title> 
        <style type="text/css">
            #drop_zone {                display: block;                border: 2px dashed #BBB;                padding: 25px 5px;                text-align: center;                font-size: 20pt;                color: #BBB;                border-radius: 5px;
            }            
            #drop_zone.hovering {                -webkit-box-shadow: inset 0px 0px 50px #BBB;                -moz-box-shadow: inset 0px 0px 50px #BBB;                -o-box-shadow: inset 0px 0px 50px #BBB;                box-shadow: inset 0px 0px 50px #BBB;
            }            
            #file-upload-box {                margin: 40px 25px;                padding: 10px;                border: 1px solid #BBB;
            }            
            #description:first-line {                margin-left: 42px;
            }            
            #output_area {                text-align: center;                display: flex;                flex-wrap: wrap;                align-content: space-between;                position: absolute;                left: 0;                right: 0;                top: 106px;                overflow: auto;                bottom: 0;
            }            
            #file-upload-box {                position: absolute;                top: 45px;                bottom: 45px;                left: 20px;                right: 20px;                background-color: #fff;                overflow: auto;
            }            
            .upload-img-itme {                color: #333;                width: 170px;                margin: 10px;                color: #333;                flex: 1;
            }            
            .upload-img-itme a.rimg-name {                overflow: hidden;                text-overflow: ellipsis;                white-space: nowrap;                padding: 5px;                display: block;
            }            
            .d-image {                box-shadow: 0 0 10px #bbb;                border-radius: 20px;                overflow: hidden;                width: 170px;                height: 170px;                display: inline-block;                z-index: 344;                background-color: #cecece;                position: relative;                transition: all 1s;                -moz-transition: all 1s;                -webkit-transition: all 1s;                -o-transition: all 1s;                cursor: pointer;
            }            
            .d-image:hover:after {                display: block;
            }            
            .d-image:after {                content: "×";                font-size: 44px;                text-align: center;                width: 50%;                margin: auto;                position: absolute;                top: 50%;                display: none;                left: 50%;                -webkit-transform: translate(-50%, -50%);                -ms-transform: translate(-50%, -50%);                transform: translate(-50%, -50%);
            }            
            .d-image:hover> img {                -webkit-filter: blur(5px);                -moz-filter: blur(5px);                -ms-filter: blur(5px);                filter: blur(5px);
            }        </style>
    </head>
   <body ondrop="return false" ondragover="return false">
        <!--防止拖拽跳轉(zhuǎn)-->
        <div id="file-upload">
            <div id="file-upload-box">
                <label id="drop_zone">將文件拖拽到這里或點擊這里                    <input multiple id="files" type="file" hidden="hidden" style="display: none;" name="files[]" />
                </label>
                <div id="output_area"></div>
            </div>
        </div>
        <div style="position: absolute; bottom: 10px; left: 40px; right: 40px;text-align: center;">
            <button onclick="demo.ImageLs=[];reloadDiv();" style="padding: 5px 10px; background: #fff; border: 1px #000 solid; cursor: pointer;">清空</button>
            <button onclick="alert('上傳')" style="padding: 5px 10px; background: #fff; border: 1px #000 solid; cursor: pointer;">上傳</button>
        </div>
        <script>
            var ImgType = ["gif", "jpeg", "jpg", "bmp", "png", "ico", "webp"];            function getFileUrl(fileObj) {                return window.URL.createObjectURL(fileObj);
            }            //拖拽功能
            var output = document.getElementById('output_area');            var dropZone = document.getElementById('drop_zone');            if(!(('draggable' in dropZone) && ('ondragenter' in dropZone) &&
                    ('ondragleave' in dropZone) && ('ondragover' in dropZone) &&                    window.File)) {                document.getElementById('error_msg').style.display = 'block';                document.getElementById('demo_area').style.display = 'none';
            } else {                function handleFileDragEnter(e) {
                    e.stopPropagation();
                    e.preventDefault();                    this.classList.add('hovering');
                }                function handleFileDragLeave(e) {
                    e.stopPropagation();
                    e.preventDefault();                    this.classList.remove('hovering');
                }                function handleFileDragOver(e) {
                    e.stopPropagation();
                    e.preventDefault();
                    e.dataTransfer.dropEffect = 'copy';
                }                function handleFileDrop(e) {
                    e.stopPropagation();
                    e.preventDefault();                    this.classList.remove('hovering');
                    FilesGetImgSv(e.dataTransfer.files);
                }
                dropZone.addEventListener('dragenter', handleFileDragEnter, false);
                dropZone.addEventListener('dragleave', handleFileDragLeave, false);
                dropZone.addEventListener('dragover', handleFileDragOver, false);
                dropZone.addEventListener('drop', handleFileDrop, false);
            }            //<input
            function handleFileSelect(evt) {
                FilesGetImgSv(evt.target.files);
            }            document.getElementById('files').addEventListener('change', handleFileSelect, false);            //圖片文件 過濾 顯示
            function FilesGetImgSv(files) {//獲取文件
                for(var i = 0, f; f = files[i]; i++) {                    if(RegExp("\.(" + ImgType.join("|") + ")$", "i").test(f.name.toLowerCase())) { //這里是簡單后綴驗證,可添加f.type驗證格式
                        f.BolbUrl = getFileUrl(f);
                        demo.ImageLs.push(f);
                    }
                }
                reloadDiv();
            }            function reloadDiv(){//刷新視圖
                var t="";
                demo.ImageLs.forEach(function(v,i){
                    t=t+`<div class="upload-img-itme"><div class="d-image" onclick="demo.removeThisUpImg(${i})">![](${v.BolbUrl})</div><a class="rimg-name"><strong>${v.name}</strong></a></div>`;
                });  
                document.getElementById("output_area").innerHTML=t;
            }            var demo = {                ImageLs: [],                removeThisUpImg: function(index) {
                    demo.ImageLs.splice(index, 1); 
                    reloadDiv();
                }
            };        </script>
    </body> </html>

關(guān)于HTML5制作圖片拖拽上傳預(yù)覽組件的方法就分享到這里了,當然并不止以上和大家分析的辦法,不過小編可以保證其準確性是絕對沒問題的。希如果喜歡本篇文章,不妨把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI