简体   繁体   中英

If/else statement to display/hide image

The function should go like: if an integer value for a variable provided by a core module is larger than 0 then an image should be displayed, else it should remain hidden.

The Coremodule is constructed so if I in my *.js file write: data.truck.retarderBrake (which is an integer). Then the coremodule will return the current integervalue .

So my "pseudo code" will look something like this:

if (data.truck.retarderBrake>0) {
    show.image ('images/RetarderON.png');
    } else {
    hide.image ('images/RetarderON.png');
}

In my HTML code I have a statement for the image:

    <div class="RetarderOn"></div>

and the CSS looks like this:

.RetarderOn {
  background-image: url("images/RetarderON.png");
  position: absolute;
  left: 851px;
  top: 13px;
  width: 92px;
  height: 71px;
  visibility: hidden;
}

Can I do it this way? And what would the correct syntax for the JS if statement be. Maybe I can define all the properties of the image in the JS file instead of the CSS file?

You can set the visibility property for that specific element via its style object; you can find the element via querySelector (if I assume there's only one of them), which accepts any valid CSS selector and returns the first match:

document.querySelector(".RetarderOn").style.visibility = data.truck.retarderBrake > 0 ? "visible" : "hidden";

If there are multiple matches, use querySelectorAll and pick the relevant one from the resulting NodeList .

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