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:
<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="Iw==" alt="eW91ciBpbWFnZQ==" />
</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 的背景图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将上传的图片预览为 div 的背景图片?


- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07