(jQuery) Toggle div style “display:none” to “display:inline”

后端 未结 3 1432
走了就别回头了
走了就别回头了 2021-02-13 20:47

I have 2 divs which and I want to be able to toggle between them onClick of a button (currently using .toggle();)

The div that shows on the page is div1. This div has th

3条回答
  •  萌比男神i
    2021-02-13 21:35

    Here is a simple way to do it:

    1. For the html, we have a simple button to call the "toggleFunction" that will add and remove display classes to our Div elements as necessary.

      Now showing "Div 1"

      Now showing "Div 2"

    2. We'll set the default display properties of Div 1 and Div 2 to "inline" and "none" respectively, so that by default:

      • Div 1 is Shown, and
      • Div 2 is Hidden.

    Here is the css for that:

    #div1 {
        display: inline;
        color:blue;
    }
    
    #div2 {
        display: none;
        color:red;
    }
    
    .display-none {
        display: none !important;
    }
    
    .display-inline {
        display: inline !important;
    }
    
    1. Finally, we'll use Jquery to add and remove the "display-none" and the "display-inline" classes to Div 1 and Div 2 respectively by calling our "toggleFunction" when the button is clicked.

    Here is the Jquery for that:

      function toggleFunction() {
        $("#div1").toggleClass("display-none");    
        $("#div2").toggleClass("display-inline");    
      }
    

    You can try it out on codepen here: http://codepen.io/anon/pen/vEbXwG

提交回复
热议问题