-1
<div id="back" style=" background-repeat:no-repeat;  border:thin solid black;     width:200px; height:230px;" >
<input type="file" id="image_file" name="image_file[]" multiple     onchange="fileSelected();" />
<output id="list"></output>

function fileSelected() {
    // get selected file element
    var oFile = document.getElementById('image_file').files[0];

    // filter for image files
    var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
    if (! rFilter.test(oFile.type)) {
        document.getElementById('list').style.display = 'block';
        return;
    }


    // get preview element
    var oImage = document.getElementById('back');

    // prepare HTML5 FileReader
    var oReader = new FileReader();

    oReader.onload = function(e){

        // e.target.result contains the DataURL which we will use as a source of the image
        oImage.style.backgroundImage = e.target.result;

        oImage.onload = function () { // binding onload event

            // we are going to display some custom image information here
            sResultFileSize = bytesToSize(oFile.size);
            document.getElementById('list').style.display = 'block';
            document.getElementById('list').innerHTML = 'Name: ' + oFile.name;
        };
    };

    // read selected file as DataURL
    oReader.readAsDataURL(oFile);
}

我想根据文件选择设置 div 的背景,但我无法实现。

我可以使用 img 元素来做到这一点,但这不是我的要求。

每次使用文件输入选择 img 时,我都想更改 div 背景。

提前谢谢...请帮助

4

1 回答 1

0

尝试换行:

 oImage.style.backgroundImage = e.target.result;

至:

 oImage.style.backgroundImage = "url(" + e.target.result + ")";
于 2013-09-16T21:44:40.083 回答