如何将上传的图片预览为 div 的背景图片? [英] How to preview an uploaded image as the background image of a div?

查看:14
本文介绍了如何将上传的图片预览为 div 的背景图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

<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>

相关的 HTML:

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

非常酷.但是,我想要将上传的图像显示为 div 的背景图像,例如:

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 class="image" style="background-image:url('');"></div>

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

I know that, logically, I would have to replace

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

类似的东西

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

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

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

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

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

谢谢.

推荐答案

您可以像在 CSS 文件中一样使用 CSS 速记.我建议以下内容以避免重复和对齐问题:

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

<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>

变化就是这样的一行

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

这篇关于如何将上传的图片预览为 div 的背景图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆