简体   繁体   中英

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

I want to load an image background inside a specific div instead of <img src=""> tag using Javascript.

As it is now the code with the <img/> tag is:

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

I tried something like that:

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

But it doesn't work and returns an error.

What is the correct syntax to make it work?

It's easy to miss typos in long concatenated statements. The fixed code is:

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

Or broken down for easier reading

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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