javascript 如何将上传的图片预览为 div 的背景图片?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16312930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:10:41  来源:igfitidea点击:

How to preview an uploaded image as the background image of a div?

javascriptjqueryimageupload

提问by Hemkesh Molla

I want to preview an uploaded image file in a div. I have done a bit of research and I have found this piece of code from this post, it is the code to preview an uploaded image file, but in an <img>tag:

我想在 div 中预览上传的图像文件。我做了一些研究,我从这篇文章中找到了这段代码,它是预览上传的图像文件的<img>代码,但在一个标签中:

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

The associated HTML:

相关的 HTML:

<body>
    <form id="form1" runat="server">
        <input type='file' onchange="readURL(this);" />
        <img id="blah" src="#" alt="your image" />
    </form>
</body>

Very cool. However, what I want is to display the uploaded image as the background image of a div, an example of which would be like this:

很酷。但是,我想要的是将上传的图像显示为 div 的背景图像,示例如下:

<div class="image" style="background-image:url('');"></div>

<div class="image" style="background-image:url('');"></div>

I know that, logically, I would have to replace

我知道,从逻辑上讲,我必须更换

$('#blah').attr('src', e.target.result);

$('#blah').attr('src', e.target.result);

with something like

$('div.image').attr('style', e.target.result);.

$('div.image').attr('style', e.target.result);.

But how to make the path of the image go into the value of the 'background-image' property?

但是如何让图片的路径进入'background-image'属性的值呢?

And yes, do I need to link to the JQuery library for this?

是的,我需要为此链接到 JQuery 库吗?

Thank you.

谢谢你。

回答by Ding

You could use CSS shorthand just like in a CSS file. I recommend the following to avoid repeating and alignment issues:

您可以像在 CSS 文件中一样使用 CSS 速记。我建议采取以下措施以避免重复和对齐问题:

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#objectID').css('background', 'transparent url('+e.target.result +') left top no-repeat');
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

The change is the line like this

变化是这样的线

$('#objectID').css('background', 'transparent url('+e.target.result +') left top no-repeat');