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

查看:130
本文介绍了如何预览上传的图片作为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天全站免登陆