简体   繁体   中英

How to add a dynamic add background-image in knockoutjs binding?

I am using knockout.js to bind the li elements

as per following :

<ul class="grid" data-bind="foreach: articledashboard">
    <li data-bind="style: { background-image: url(AuthorImage)}">
        <label data-bind="attr: { title: Title }, text: Title"></label>
    </li>
</ul>

My requirement is to set background image of li element, but my code is not working

Can you give me correct syntax?

Use backgroundImage instead of background-image , and set the value as a string:

<li data-bind="style: { backgroundImage: 'url(' + AuthorImage() + ')'}">

See the documentation

Edit:

As RP Niemeyer pointed out, you can also use 'background-image' :

<li data-bind="style: { 'background-image': 'url(' + AuthorImage() + ')'}">

Note that this supposes that AuthorImage is an observable. If it is not, use AuthorImage .

html:

<div style="width:100%;height:100%;"  
    data-bind='style:{ background: "url(" + image_url() + ") center/cover"} '
></div>

js:

<script>
    function ViewModel(){
        var self = this;
        self.image_url = ko.observable("");
    }
</script>

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