How to preview an uploaded image as the background image of a div?(如何将上传的图片预览为 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:
相关的 HTML:
非常酷.但是,我想要将上传的图像显示为 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:
变化就是这样的一行
这篇关于如何将上传的图片预览为 div 的背景图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!