javascript jQuery - css("background-image", variable) 不起作用:(
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5401612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - css("background-image", variable) doesn't work :(
提问by Alex
I'm trying to save the background-image of a element, remove it and then maybe add it back later.
我正在尝试保存元素的背景图像,将其删除,然后再将其添加回来。
var current_bg_image = $("#div").css("background-image");
if(something){
$("#div").css("background-image", "none");
}else{
$("#div").css("background-image", current_bg_image); // not working...
}
The part where the background image is supposed to be added back doesn't work...
But if I change current_bg_image
with "url(something.jpg)"
it works. It seems that css() doesn't work with variables?
其中,背景图像是应该加回的部分不工作......但是,如果我改变current_bg_image
与"url(something.jpg)"
它的工作原理。似乎 css() 不适用于变量?
回答by Havihavi
Had the same problem, solved by this:
有同样的问题,解决了这个:
var id = $(this).attr("src");
//alert(id);
$('#div').css({'background-image': 'url(' + id + ')',
});
var id = $(this).attr("src");
//alert(id);
$('#div').css({'background-image': 'url(' + id + ')',
});
回答by leek
Your code works fine for me using jQuery 1.5.1. I believe what you will get once saving the background-image value to current_bg_image
is the full path to the image, so try reading that value using Firebug or alert(current_bg_image)
and ensure it is what you think it should be.
您的代码使用 jQuery 1.5.1 对我来说效果很好。我相信一旦将 background-image 值保存到图像current_bg_image
的完整路径,您将获得什么,因此请尝试使用 Firebug 读取该值,或者alert(current_bg_image)
确保它是您认为应该是的。