简体   繁体   English

将预加载的图像绑定到div背景图像

[英]Binding preloaded image to div background-image

I have preloaded 2 images using below statements: 我已经使用以下语句预加载了2张图片:

    window.imgOK = $('<img src="' + '@Url.Content("~/images/OK.gif")' + '">');
    window.imgNOK = $('<img src="' + '@Url.Content("~/images/NOK.gif")' + '">');

Also, I have a div and in a certain moment and depending on some conditions I want to bind one of the above image to the div background-image, I mean, I want to set the div background-image with one of the above images. 另外,我有一个div,并且在某些情况下,根据某些条件,我想将上述图像之一绑定到div背景图像,我的意思是,我想用上述图像之一设置div背景图像。

For example, if some condition in my code is not satisfied, then I would like to do something like below in order to update div background-image as: 例如,如果我的代码中的某些条件不满足,那么我想做以下类似的事情来将div背景图像更新为:

$('#MyDiv').css("background-image", window.imgNOK);

and if condition is satisfied: 如果满足条件:

$('#MyDiv').css("background-image", window.imgOK);

but it is not working so how to do this? 但是它不起作用,怎么办呢?

您需要根据图像的来源(而不是图像标签本身)将其分配为URL,以使其成为背景。

$('#MyDiv').css("background-image", "url(" + window.imgOK.attr('src') + ")"  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM