Home>

I am currently using a template with the following code.

. owl-theme .owl-controls .owl-page: nth-child (1) {
    background: url (test1.png) center;
    background-size: 100px 100px;
}
.owl-theme .owl-controls .owl-page: nth-child (2) {
    background: url (test2.png) center;
    background-size: 100px 100px;
}
.owl-theme .owl-controls .owl-page: nth-child (3) {
    background: url (test3.png) center;
    background-size: 100px 100px;
}

Here, I want to dynamically change the image file (test1.png, test2.png, test3.png) to be read from HTML, but when I use a custom property, an error "EXPECTED RBRACE" appears. Does n’t work ...

If this processing is implemented in JavaScript, how can I write it?

css
  • Answer # 1

    If you use JavaScript, put the image URL in thedata-*attribute and set it to thebackground-imageproperty of each element with JavaScript. (Operation check link).

    
       
       
       
    
    . owl-controls {
      display: flex;
    }
    .owl-page {
      flex: 1;
      height: 50vh;
      background-position: center;
      background-size: 100px 100px;
    }
    const list = document.getElementsByClassName ("owl-page");
    for (const e of list) {
      e.style.backgroundImage = `url (${e.dataset.image})`;
    }

    Alternatively, theurlfunction including the image URL can be specified as a custom property in thestyleattribute of each element. (Check link for operation)

    
       
       
       
    
    . owl-controls {
      display: flex;
    }
    .owl-page {
      flex: 1;
      height: 50vh;
      background-image: var (-background);
      background-position: center;
      background-size: 100px 100px;
    }

    According to CSS Values ​​and Units Level 3, you can get element attribute values ​​using theattrfunction. Therefore, if you use this, you can use thedata-*attribute andattrfunction as shown below to make it easier for the questioner to achieve. (Operation confirmation link). However, as you can see from the link for confirming the operation,There are no browsers that currently support this function, so the current situation is to select one of the above two methods. It becomes.

       § 9.2. Attribute References: attr ()   

    The attr () function is allowed as a component value in properties applied to an element or pseudo-element.It returns the value of an attribute on the element.If used on a pseudo-element, it returns the value of the attribute on the pseudo-element's originating element.

    
       
       
       
    
    . owl-controls {
      display: flex;
    }
    .owl-page {
      flex: 1;
      height: 50vh;
      background-image: attr (data-image url);
      background-position: center;
      background-size: 100px 100px;
    }

Trends