简体   繁体   中英

How can I use CSS to show and hide multiple elements at once?

I found this article that looked like exactly what I wanted, but I can't seem to get it to work at all. Since it is well over a year old, I thought perhaps something may have changed, or that there might be a simpler way to do it by now.

That is to say, I cannot get the method I linked above to work. I copied and pasted exactly, and used <body onLoad="javascript_needed()"> because I wasn't sure where $(document).ready(function ()... was supposed to go. I am, sadly, quite unfamiliar with Javascript.

Use something like this;

<script>

  $(document).ready(function(){
    //Code goes in here.
  });

</script>

Don't forget to load the jQuery library at the same time from http://jquery.com/

Also, you are going to want to read up on selectors.

Using $("#myElement") will select elements that have an id of "myElement".

Using $(".myElement") will select elements that have a class of "myElement".

So;

<div class="hideMe">Content</div>
<div class="hideMe">Content</div>
<div class="hideMe">Content</div>
<div class="doNotHideMe">Content</div>

<input type="button" class="ClickMe" value="click me"/>

<script>

  $(function(){
    $(".ClickMe").click(function(){
      $(".hideMe").hide(250);
    });
  });

</script>

edit

If you want to link to the jquery library online then use;

<script src="http://code.jquery.com/jquery-1.6.1.min.js" type="text/javascript"></script>

If you download the library and insert the js file into your project then use;

<script src="/yourPathToTheLibrary/jquery-1.6.1.min.js" type="text/javascript"></script>

The $ syntax is all part of jQuery. If you wish to use jQuery then somewhere in your code, use a script tag as in your post:

<script>
    $(function() {
        $('.selector').hide(250);
    });
</script>

If you want pure JavaScript, then there is a little more overhead. Not including the document ready stuff (which can be a lot of extra code to do it right...See example: here ).

<script>
    elements = document.querySelectorAll('.selector');

    for(int i=0,len=elements.length;i<len;++i) {
        elements[i].style.display = 'none';
    }
</script>

You can put that in a function if you would like. To show the elements set the display attribute to '' .

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