我正在尝试将背景图像添加到动态生成的div中.当我为背景添加CSS属性时,如下所示,它会破坏我的插件:
$("<div>", {
'class': "iviewer_image_mask",
css: "background: url('http://somesite.com/path/to/image.jpg');"
}).appendTo(this.container);
Run Code Online (Sandbox Code Playgroud)
有人知道我做错了添加背景图片吗?
Ric*_*ann 25
当然你只能使用字符串添加它,但我更喜欢这种方式,因为它更可读,更清晰.
$("<div>", {
'class': "iviewer_image_mask",
css: {
"background": "url('http://somesite.com/path/to/image.jpg')"
}
}).appendTo(this.container);
Run Code Online (Sandbox Code Playgroud)
Chr*_*son 19
根据这个SO问题中报告的一些基准测试,我相信使用jQuery创建HTML元素的最有效方法是:
$('<div class="iviewer_image_mask" style="background: url(http://somesite.com/path/to/image.jpg);"></div>').appendTo(this.container);
Run Code Online (Sandbox Code Playgroud)
或者为了一些额外的可读性:
var elm = '<div class="iviewer_image_mask" ' +
'style="background: url(http://somesite.com/path/to/image.jpg);">'+
'</div>';
$(elm).appendTo(this.container);
Run Code Online (Sandbox Code Playgroud)
$("<div>").attr({
'class': "iviewer_image_mask",
'style': "background: url('http://somesite.com/path/to/image.jpg');"
}).appendTo("body");
Run Code Online (Sandbox Code Playgroud)
如果你真的需要通过属性追加它.
$("<div>")
.addClass('iviewer_image_mask')
.css('background', "url('http://somesite.com/path/to/image.jpg')")
.appendTo(this.container);
Run Code Online (Sandbox Code Playgroud)