【问题标题】:Hide/Show Elements and Change Button隐藏/显示元素和更改按钮
【发布时间】:2019-10-26 10:56:10
【问题描述】:

我想要一个按钮,当点击时,隐藏一个元素并显示另一个元素,并让按钮在点击时更改文本(我想我得到了这部分)。另外,我想在加载页面时只显示一个元素,当单击按钮时,只显示另一个元素。我目前使用的代码几乎可以正确完成此操作,但是单击按钮后,会显示隐藏的元素(需要),但显示的其他元素并未隐藏。这是我的代码(我使用的是基本 JS,我不想使用 jQuery)。

HTML

<html>
<body>
  <div>
    <span>E-Mail or Phone<br>
    </span>
    <button onclick="emph()" id="emphbtn" type="button">Use Phone</button>
  </div>
  <div id="phbox" style="display: none;">
    <label for="phone">Phone</label><input id="phone" type="tel" />
  </div>
  <div id="embox">
    <label for="mail">E-Mail</label><input id="mail">
  </div>
</body>

和javascript

function emph() {
    // get the clock
    var myPhone = document.getElementById('phbox');

    // get the current value of the clock's display property
    var displaySetting = myPhone.style.display;

    // also get the clock button, so we can change what it says
    var switchbtn = document.getElementById('emphbtn');

    // now toggle the clock and the button text, depending on current state
    if (displaySetting == 'block') {
      // clock is visible. hide it
      myPhone.style.display = 'none';
      // change button text
      switchbtn.innerHTML = 'Use Phone';
    }
    else {
      // clock is hidden. show it
      myPhone.style.display = 'block';
      // change button text
      switchbtn.innerHTML = 'Use Email';
    }
  }

【问题讨论】:

    标签: javascript html user-interface button input


    【解决方案1】:

    您还需要切换您的电子邮件输入框

    function emph() {
      // get the clock
      var myPhone = document.getElementById('phbox');
      var myEmail = document.getElementById('embox');
    
      // get the current value of the clock's display property
      var displaySetting = myPhone.style.display;
    
      // also get the clock button, so we can change what it says
      var switchbtn = document.getElementById('emphbtn');
    
      // now toggle the clock and the button text, depending on current state
      if (displaySetting == 'block') {
        // clock is visible. hide it
        myPhone.style.display = 'none';
        myEmail.style.display = 'block';
        // change button text
        switchbtn.innerHTML = 'Use Phone';
      } else {
        // clock is hidden. show it
        myPhone.style.display = 'block';
        myEmail.style.display = 'none';
        // change button text
        switchbtn.innerHTML = 'Use Email';
      }
    }
    <div>
      <span>E-Mail or Phone<br></span>
      <button onclick="emph()" id="emphbtn" type="button">Use Phone</button>
    </div>
    <div id="phbox" style="display: none;">
      <label for="phone">Phone</label><input id="phone" type="tel" />
    </div>
    <div id="embox">
      <label for="mail">E-Mail</label><input id="mail">
    </div>

    【讨论】:

      猜你喜欢
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多