标签会在Chrome中几秒后更改回第一个标签页

时间:2018-05-10 22:42:38

标签: javascript tabs

我有一个页面,上面有5个标签。设置为在页面加载时打开第一个选项卡。几秒钟后,当我单击其中一个选项卡时,它会再次更改回第一个选项卡。它应该保留在单击的选项卡上,直到单击其他内容而不返回到第一个选项卡。

它适用于Firefox,但不适用于ChromeSafari

网址为https://vcs.org/donate-now/

javascript代码就是这个 -

 function openCity(evt, cityName) {
     var i, tabcontent, tablinks;
     tabcontent = document.getElementsByClassName("tabcontent");
     for (i = 0; i < tabcontent.length; i++) {
         tabcontent[i].style.display = "none";
     }
     tablinks = document.getElementsByClassName("tablinks");
     for (i = 0; i < tablinks.length; i++) {
         tablinks[i].className = tablinks[i].className.replace(" active", "");
     }
     document.getElementById(cityName).style.display = "block";
     evt.currentTarget.className += " active";
 }

 // Get the element with id="defaultOpen" and click on it


 window.onload=function(){
     document.getElementById("defaultOpen").click();
 };

请帮忙!!!我很感激!!

1 个答案:

答案 0 :(得分:0)

所以你在打电话......

window.onload = function () {
    document.getElementById("defaultOpen").click();
};

然后触发另一个onclick事件...

<li>
    <button class="tablinks" onclick="openCity(event, 'Donate')" id="defaultOpen"><a href=""></a><h1>Donate</h1> MAKE A DIFFERENCE NOW</button>
</li>

我建议在默认选项卡上设置活动,然后在选择不同选项卡时删除。这是一个快速而又肮脏的例子。

var tabLinks = document.getElementsByClassName('tablinks');

function openCity(evt) {
  var tabcontent = document.getElementsByClassName("tabcontent");
  for (var i = 0; i < tabcontent.length; i++) {
    if (tabcontent[i].id === evt.target.name) {
      tabcontent[i].style.display = "block";
    } else {
      tabcontent[i].style.display = "none";
    }
  }

  for (let a of tabLinks) {
    a.className = 'tablinks'
  }

  evt.currentTarget.className += ' active';
}


for (let t of tabLinks) {
  t.addEventListener('click', function(event) {
    openCity(event);
  });
}
button.active {
  background-color: lightblue !important;
}
<ul>
  <li>
    <button class="tablinks active" name="defaultOpen"><a href=""></a><h1>Donate</h1> MAKE A DIFFERENCE NOW</button>
  </li>
  <li>
    <button class="tablinks" name="other"><a href=""></a>Other</button>
  </li>
  <ul>

    <div id="defaultOpen" class="tabcontent" style="display:block;">
      defaultOpen content
    </div>

    <div id="other" class="tabcontent" style="display:none;">
      other content
    </div>