开发者

Image visibility one

开发者 https://www.devze.com 2023-01-31 09:56 出处:网络
I have a few images with: visibility:hidden and an onClick event which sets its visibility to visible. Images have an id of Img_(somenumber)

I have a few images with: visibility:hidden and an onClick event which sets its visibility to visible. Images have an id of Img_(somenumber)

H开发者_开发知识库ow can I make so that when one image is visible all others should be hidden?


Using jquery you could try the following:

  • Add a class to the set of images you want to manipulate their visibility. e.g.

Then for each image you could to the following for the onclick event:

<img src="{img_src}" class="myImages" onclick="$('img.myImages').hide(); $(this).show();" />

The above, of course, requires that you change each image tag.

If you cannot do that (large number of images), then try using a function that will be triggered when the document loads and will add a handler for the 'onclick' event of each image. Again this easy easily achieved using jquery or another js library.


There are a ton of ways to do this. I'm pretty sure you will want to think through it more. BUT, For an answer without jQuery. Add this as your onClick handler. Make sure you pass the this keyword.

<img onclick="toggleVisible(this);" src="" />

Include this function in your page somewhere:

function toggleVisible(clickedLI) {
    var imgs = document.getElementsByTagName('img');
    var i = imgs.length;
    while (i--) {
        var img = imgs[i];
        if (img.id.indexOf('Img_' == 0)) { 
            img.style.visibility = img.parentNode == clickedLI ? 'visible' : 'hidden';
        }
    }
}

The first problem you will run into is that there is no way to bring back the hidden images. They are there, taking up space in the document, but they won't respond to the click events (at least not in Chrome.) Consider giving more detail in your question. As andreas said, if you have a lot of images there are more efficient ways.

0

精彩评论

暂无评论...
验证码 换一张
取 消