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

后端 未结 3 1371
走了就别回头了
走了就别回头了 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条回答
  • 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.

      <button onclick="toggleFunction()" >Click to toggle</button>

      <div id="div1" class=" " > Now showing "Div 1" </div>

      <div id="div2" class=" " > Now showing "Div 2" </div>

    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

    0 讨论(0)
  • 2021-02-13 21:37

    I would use .toggleClass() as toggle switches between display: inline; and display: block;

    Create a hidden and inline class and just toggle those.

    0 讨论(0)
  • 2021-02-13 21:51

    Using plain JavaScript, you could use:

    document.getElementById('div1').style.display = 'none';
    document.getElementById('div2').style.display = 'inline';
    
    0 讨论(0)
提交回复
热议问题