切换两个div jQuery之间的隐藏/显示

时间:2016-10-01 16:17:31

标签: javascript jquery html css

我试图让链接工作,以便在两个div之间切换hide / show。没有什么奇怪的,我已经看到了很多这样做的例子。 我的基本html结构如下:

<div id="wrapper">
   <div id="tog_A">
   <div id="tog_B">
</div>

<a href="#" id="link">Toggle</a>

和CSS:

#tog_A {
  display:block;
}
#tog_A {
  display:block;
}

但是,当我添加我发现的不同解决方案时,似乎与我的网站使用的其他一些JavaScript代码存在冲突。 在谈到JavaScript时,我真的是一个真正的n00b,所以也许有人可以指出我正确的方向,也许可以帮助我将现有的代码与新的代码结合起来。

似乎存在冲突的现有JavaScrip:

//Load when dom ready
jQuery(function() {
// click listener for anchors
jQuery(document).on("click",'a[href^="#"]', function(e) {

// prevent click and side effects 
    e.preventDefault();

// do the scroll
  jQuery('body, html').animate({
    scrollTop : jQuery(this.hash).offset().top
  });

//change state of button
var oldHash = jQuery(this.hash).attr("id").split("-");
var oldNr = parseInt(oldHash[1],10);
var nrOfAllSections = jQuery('[id^="section-"]').length;
var nr = oldNr == nrOfAllSections ? 1 : oldNr+1;
if(oldNr == nrOfAllSections) {
  jQuery(this).text("Top ▴");
    } else {
  jQuery(this).text("Down ▾");
    }
var newHash = "#"+oldHash[0]+"-"+ nr;
jQuery(this).attr("href", newHash);
});

jQuery(document).on('click', "#scrollToInfo", function(e) {
   e.preventDefault();
   var nrOfAllSections = jQuery('[id^="section-"]').length;
   var hrefHash = "#section-" + nrOfAllSections;
   var ypos = jQuery(hrefHash).offset().top;
   window.scrollTo(0, ypos);
   jQuery('a#scrollToBottom').text("Top ▴").attr("href", "#section-1");
 });

});

2 个答案:

答案 0 :(得分:0)

使用此技术

  $("#link").click(function () {
       if ($("#tog_A").is(":visible")) {
         $("#tog_A").hide();
         $("#tog_B").show();
      } else {
        $("#tog_B").hide();
        $("#tog_A").show();
      }
    });

答案 1 :(得分:0)

<head>
 <script>
  var toggle = function() {
  var mydiv = document.getElementById('tog_A');
  var mydiv2 = document.getElementById('tog_B');
  if (mydiv.style.display === 'none' || mydiv.style.display === '' ||      mydiv2.style.display === 'none' || mydiv2.style.display === '')
   mydiv.style.display = 'block';
    mydiv2.style.display = 'block';

 else
   mydiv.style.display = 'none'
   mydiv2.style.display= 'none'
}

</script>
</head>
<body>
<div id="wrapper">
   <div id="tog_A" style="display:none;">
   <div id="tog_B" style="display:none;" >
</div>

  <a href="#" onclick="toggle();" id="link">Toggle</a>
<body>
相关问题