Show/Hide Requires a Double-click

前端 未结 2 1915
闹比i
闹比i 2021-01-28 10:56

I\'m writing a basic show/hide function that displays a block of content and changes some text from \"Show More Benefits\" to \"Show Less Benefits\" (and vice versa).

Fo

2条回答
  •  [愿得一人]
    2021-01-28 11:18

    The reason you need to click twice:

    element.style.display refers to inline styles only.

    Initially, your elements do not have a style-attribute. As a result, element.style.display returns the empty String:

    function showHide(c,t) {
      var c = document.getElementById("content");
      var t = document.getElementById("text");
      console.log("c.style.display is:" + c.style.display);
      if (c.style.display === "none") {
        c.style.display = "block";
        t.innerHTML = 'See Less Benefits';
      } else {
        t.innerHTML = 'See More Benefits';
        c.style.display = "none";
      }
    }

    $2B lorem

    $2B ipsum

    $100 ipsum

    32% ipsum

    See More Benefits

    Bad but simple solution:

    Add the style="display: block" to your initial HTML:

    function showHide(c,t) {
      var c = document.getElementById("content");
      var t = document.getElementById("text");
      console.log("c.style.display is:" + c.style.display);
      if (c.style.display === "none") {
        c.style.display = "block";
        t.innerHTML = 'See Less Benefits';
      } else {
        t.innerHTML = 'See More Benefits';
        c.style.display = "none";
      }
    }
    
    

    See More Benefits

    Better solution:

    Instead of toggling style.display between none and block, instead toggle the universal attribute hidden:

    function showHide() {
      const c = document.getElementById("content");
      const t = document.getElementById("text");
      
      t.textContent = c.hidden ? 'See Less Benefits' : 'See More Benefits';
      c.hidden = !c.hidden;
    }
    
    

    See More Benefits

提交回复
热议问题