javascript切换需要留下来

时间:2016-11-10 11:04:01

标签: javascript html

大家好我需要一些javascript的帮助, 我的文本有一个切换功能,你可以在www.jasperscheper.nl上看到 但是当你双击mij和home时,我想让文字停留。

这是我的代码:



var bannerText1 = document.getElementById('bannertext1');
var bannerText2 = document.getElementById('bannertext2');
var displayedBannerText = 1;

function toggleBannerText() {
  if(displayedBannerText == 1) {
    // Switch to bannertext 2
    bannerText1.className += ' hidebannertext';
    displayedBannerText = 2;
    bannertext2.className = 'welkom';
  } else {
    bannertext2.className += ' hidebannertext';
    displayedBannerText = 1;
    bannerText1.className = 'welkom';
  }
 }

<li class="knop" >    
  <button class="button" href="#"onclick="toggleBannerText()"> <h3>Home</h3></button> 
</li>
<li class="knop"> 
  <button class="button" onclick="toggleBannerText()" href="#"><h3>Over mij</h3></button>
</li>
&#13;
&#13;
&#13;

提前感谢,

Jasper Scheper。

1 个答案:

答案 0 :(得分:1)

问题:每次点击任何一个按钮时都在调用函数toggleBannerText(),按钮的点击事件没有区别,所以每次点击都会假设你需要显示除显示之外的其他文本。

解决方案:更改HTML以将参数传递到函数中,说明要显示的部分。例如:toggleBannerText('Home')

<li class="knop" >    
<button class="button" href="#"onclick="toggleBannerText('Home')"> <h3>Home</h3></button> 
</li>

<li class="knop"> 
<button class="button" onclick="toggleBannerText('Over')" href="#"><h3>Over mij</h3>
</button>  <!-- There was a typo you had a </a> here I changed it -->
</li>

现在更改您的函数以接受参数并显示特定的文本。

function toggleBannerText(section) {
  if(section === "Over") {
    // Switch to bannertext 2
    bannerText1.className = 'hidebannertext';      // I have removed the +  
    bannertext2.className = 'welkom';
  } 
  else if (section === "Home"){
    bannertext2.className = 'hidebannertext';      // + has been removed 
    bannerText1.className = 'welkom';
   }
  else{
    // none of the two buttons were clicked.
  }
}

I have tested this code against your site and its working fine