开发者

How do I swap triangle icons when doing expanding/collapsing divs with Javascript/CSS

开发者 https://www.devze.com 2022-12-21 07:10 出处:网络
I have a div that I want to toggle between displaying or not when a user clicks on a piece of text. I have a javascript function that toggles a div on or off. That works fine. What I don\'t know how t

I have a div that I want to toggle between displaying or not when a user clicks on a piece of text. I have a javascript function that toggles a div on or off. That works fine. What I don't know how to do is to have a triangle that points to the right or down depending on whether the div is open.

My HTML looks like this:

<a onclick="toggleDiv('myDiv');">Click here to expand or close div</a>
<div id="myDiv" style="display:none">
   ...
</div>

How do I add one of those 开发者_运维知识库triangles and have it point the right way, ideally with just HTML, Javascript, and CSS? The triangle would appear to the left of the "Click here..." string.

Thanks.


Your toggleDiv() function would be helpful to see here. Anyhow you should probably just add a class to your div, perhaps "active" or "open".

Then in your CSS, do something like:

div {
  background: url("downarrow.png") top left no-repeat; 
}

div.open {
  background: url("uparrow.png") top left no-repeat; 
}

update

You also may consider moving your JS out of your HTML entirely, you can observer the click event on the element from your JS, then add the class or remove it based on it's state. Maybe consider using a library like jQuery.


There are a number of options. First you will need the two images, let us call them uptri.jpg and downtri.jpg. Then you can create two CSS classes:

   .up{
       background-image:url(../images/uptri.jpg);
       background-repeat:no-repeat;
   }

   .down{
       background-image:url(../images/downtri.jpg);
       background-repeat:no-repeat;
   }

Then with some JavScript you can swap out the up class for the down class. I would suggest using jQuery since it makes it trivially easy.

   $("#myClicker").toggle(
         function(){$(this).removeClass('up');
                     $(this).addClass('down');
         }, 
         function(){$(this).removeClass('down');
                     $(this).addClass('up');
         }     
    );

Where myClicker is the id of your link.


You can also have an image sprite, which is a single image that has both of the arrows, preventing the need for fetching two images. Use CSS to change the position of the background image so that only one shows at a time. For example, here is one state:

#triangle {
    background-image: url(triangle.png);
    background-repeat: no-repeat;
    background-position: 0 0;
}

then use javascript to add a CSS class or directly manipulate to:

    background-position: 15px 0;

or similar to shift the next triangle into place.

0

精彩评论

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

关注公众号