简体   繁体   中英

Javascript Display/hide pictures

How to remove(hide) pictures when a certain picture is displayed based on their IDs. This is what I got so far:

function setImageinVisible(id) {
    var img = document.getElementById(id);
    img.style.visibility = 'visible';
}

First of all, the good practice says, you shouldn't mess with object's styles directly but rather toggle it's classes (because of https://en.wikipedia.org/wiki/Separation_of_concerns ). My advice is to create a state class like

.is-hidden {
  display: none;
}

and then just toggle this class on particular element with jquery, pure JS or something else, for ex.

$('.my-image').addClass('is-hidden') // to hide
$('.my-image').removeClass('is-hidden') // to show

with pure JS:

document.querySelector('.my-image').classList.add('is-hidden')
document.querySelector('.my-image').classList.remove('is-hidden')

UPDATE:

To reset previous state (set all images as hidden), before showing one:

// to add.is-hidden from every image (to hide all the images)
[].map.call(document.querySelectorAll('img'), function(el) {
    el.classList.add('is-hidden');
});
// to show choosen image
document.querySelector('.my-image').removeClass('is-hidden')

Note: toggle-vader-button , ("#Vader") , and ("#Palpatine") are all based on a project I'm working on. Substitute the IDs of your photos in

$ (document).ready(function() {
    $("#toggle-vader-button").on("click", function () {
        $("#Vader").toggle();
        $("#Palpatine").toggle();
    });
});

As one is toggled off, another is toggled on. Also note that I have Palpatine's display as "none" in my CSS so it switches on whilst Vader switches off. Both will occupy the same space also.

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