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="#" 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 的背景图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将上传的图片预览为 div 的背景图片?
基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
