问题描述
我想在 JS 中动态更改背景,并且我的图像集采用 base64 编码.我试试:
I want to change background dynamically in JS and my set of images is in base64 encoded. I try:
document.getElementById("bg_image").style.backgroundImage =
"url('http://amigo.com/300107-2853.jpg')";
完美的结果,
但我没有这样做:
document.getElementById("bg_image").style.backgroundImage =
"url('data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...')";
也没有
document.getElementById("bg_image").style.backgroundImage =
"data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...";
有什么办法吗?
推荐答案
我尝试和你做同样的事情,但显然 backgroundImage 不适用于编码数据.作为替代方案,我建议使用 CSS 类以及这些类之间的更改.
I tried to do the same as you, but apparently the backgroundImage doesn't work with encoded data. As an alternative, I suggest to use CSS classes and the change between those classes.
如果您正在动态"生成数据,则您可以动态加载 CSS 文件.
If you are generating the data "on the fly" you can load the CSS files dynamically.
function change() {
if (document.getElementById("test").className == "backgroundA") {
document.getElementById("test").className = "backgroundB";
document.getElementById("test2").className = "backgroundA";
} else {
document.getElementById("test").className = "backgroundA";
document.getElementById("test2").className = "backgroundB";
}
}
btn.onclick = change;
.backgroundA {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJk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5FKM1IQe+Mp+L4rphz+qIOBAUYeCY4p2tGrJZeH9y79mZsawFoaIRxF3JyiYxuHiMGb5KTkpFvZj4ZbYeCiXaOiKBwnxh4fnt9e3ktgZyHhrChinONs3cFAShFF2JhvCZlG5uchYNun5eedRxMAF15XEFRXgZWWdciuM8GCmdSQ84lLQfY5R14wDB5Lyon4ubwS7jx9NcV9/j5+g4JADs=");
}
<div id="test" height="20px" class="backgroundA">
div test 1
</div>
<div id="test2" name="test2" height="20px" class="backgroundB">
div test2
</div>
<input type="button" id="btn" />
我在这里摆弄它,按下按钮,它将切换 div 的背景:http://jsfiddle.净/egorbatik/fFQC6/
I fiddled it here, press the button and it will switch the divs' backgrounds: http://jsfiddle.net/egorbatik/fFQC6/
这篇关于有没有办法将背景图像设置为 base64 编码图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!