原生JavaScript上传本地图片到页面并及时预览

2017-10-30  本文已影响0人  GeniusFunny

由于缺乏数据库知识,所以图片只能上传到页面上进行预览功能。同样的,没有进行美化,只是实现了基础功能,后期会处理美化功能,然后将数据传到数据库进行储存,把这一块做成小插件,push到github上。

 var imageElem = document.getElementById('imageElem'),
        selectImages = document.getElementById('selectImages'),
        imagesList = document.getElementById('imagesList');
        loadList = [];

    selectImages.addEventListener('click',function (e) {
        if(imageElem)
            imageElem.click();
    },false);

    function handles(files) {

        if(!files.length) {
            imagesList.innerHTML = "<p>未选择图片</p>";
        } else {

            imagesList.innerHTML = "";
            var list = document.createElement('ul');
            list.classList.add('row');
            imagesList.appendChild(list);

            for(var i = 0; i < files.length; i++) {
                var li = document.createElement('li');

                li.style.marginTop = "10px";
                li.classList.add('col-md-4');
                list.appendChild(li);
                var info = document.createElement('img');
                info.src = "img/删除筛选项.png";
                info.alt = "删除";

                //li.appendChild(info);
                info.style.cursor = "pointer";
                info.addEventListener('click',function () {
                    var parent = this.parentNode;
                    parent = parent.parentNode;
                    parent.removeChild(this.parentNode);
                });


                var img = document.createElement('img');
                img.src = window.URL.createObjectURL(files[i]);
                img.onload = function () {
                    loadList.push(this.src);
                }
                //li.appendChild(img);

                img.setAttribute('width','200');  //   
                img.setAttribute('height','150');
                img.style.position = 'absolute';
                img.style.zIndex = '-1';

                var imageWidth = Math.floor(parseInt(img.getAttribute('width')));
                var infoSize = imageWidth * 0.10;


                info.setAttribute('width',infoSize + '');
                info.setAttribute('height','auto');
                info.style.marginBottom = infoSize * 1 + 'px';
                info.style.marginLeft = imageWidth * 0.9 + 'px';
                li.style.width = img.getAttribute('width') * 1.1 + 'px';
                li.style.height = img.getAttribute('width') * 1.1 + 'px';

                li.appendChild(img);
                li.appendChild(info);

            }
        }
    }

效果如下:

94E068E7-15A7-4DA6-ABAF-2EF18D3036DA.png
上一篇 下一篇

猜你喜欢

热点阅读