繁体   English   中英

如何使用 Javascript 而不是使用背景属性<img>标签?

[英]How can I use the background property using Javascript instead of using <img> tag?

我想使用 Javascript 在特定 div 中加载图像背景,而不是<img src="">标记。

因为现在带有<img/>标签的代码是:

item.prepend($('<img/>', {src: file[options.baseUrlAttribute] + '' +file[options.pathAttribute]}));

我尝试过这样的事情:

item.prepend($('<div style="background:url('file[options.baseUrlAttribute] + ''      
+file[options.pathAttribute]}')no-repeat center center / cover"></div>' ));

但它不起作用并返回错误。

使它工作的正确语法是什么?

很容易错过长连接语句中的拼写错误。 固定代码是:

item.prepend($('<div style="background:url(' + file[options.baseUrlAttribute] +file[options.pathAttribute]+')no-repeat center center / cover"></div>' ));

或为便于阅读而分解

const url = file[options.baseUrlAttribute] +file[options.pathAttribute] ;
const tag = '<div style="background:url(' + url + ')no-repeat center center / cover"></div>';
item.prepend(tag);

暂无
暂无

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

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