簡體   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