简体   繁体   中英

how to add css when button clicked

How do I add css when a button is clicked jquery?

I want to create when I click the button it will toggle hide my div and rotate the arrow to 90 degree and when a click again it will toggle show my div and rotate the arrow to -90 degree.

Here's what I've tried:

 $("#toogle_menu").click(function() { $("#jy_nav_pos_main").slideToggle("slow"), $("#toogle_menu").css({ transform: "rotate(-90deg)" }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="nav nav-tabs row margin_auto" id="jy_nav_pos_main" role="tablist"> <li>menu</li> </ul> <button id="toogle_menu" class="btn btn-light"> &raquo; </button> 

Instead of setting the style in each click, toggle the class $( "#toogle_menu" ).toggleClass( "toggled" ) and style this class in css

 $("#toogle_menu").click(function() { $("#jy_nav_pos_main").slideToggle("slow"), $("#toogle_menu").toggleClass("toggled") }); 
 .toggled { transform: rotate(-90deg); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="nav nav-tabs row margin_auto" id="jy_nav_pos_main" role="tablist"> ...... </ul> <button id="toogle_menu" class="btn btn-light"> &raquo; </button> 

Try this..

 var clicked = false; $("#toogle_menu").click(function() { var deg = clicked ? 0 : -90; $("#jy_nav_pos_main").slideToggle("slow"), $("#toogle_menu").css({ transform: "rotate("+deg+"deg)" }); clicked = !clicked; }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="nav nav-tabs row margin_auto" id="jy_nav_pos_main" role="tablist"> <li>menu</li> </ul> <button id="toogle_menu" class="btn btn-light"> &raquo; </button> 

try this...

<style type="text/css">
    .nav{
        display: none;
    }
    .rotate{
        transform: rotate(90deg);
        -webkit-transform:rotate(90deg);
        -moz-transform:rotate(90deg);
        -o-transform:rotate(90deg);
        -ms-transform:rotate(90deg);
        transition: all 0.4s linear;
    }
    #clickBtn span{
        transition: all 0.4s linear;
    }
</style>
<button type="button" id="clickBtn">Click &nbsp;&nbsp;&nbsp;<span class="fa fa-angle-right"></span></button>
<ul class="nav nav-tabs row margin_auto" id="jy_nav_pos_main" role="tablist">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
</ul>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#clickBtn").on('click',function(){
            $(this).find('span').toggleClass('rotate');
            $(".nav").slideToggle();
        });
    });
</script>

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