【问题标题】:stop div from reopening on click jQuery阻止 div 在单击 jQuery 时重新打开
【发布时间】:2017-08-15 01:28:21
【问题描述】:

我对 jQuery/JavaScript 还很陌生,我想我不理解自己的代码。

它的行为完全符合我的意愿,但是当我重新单击 .projtog 时,它会重新切换我的 .projContent,我不希望这样。我希望.projContent 在我重新单击其关联的.projtog 时关闭。 我尝试给 .projContent 一个布尔值,但并不真正知道如何处理它。

这是我的代码:

$('div.projContent').css('height', '0vh');

$('h2.projtog').click(function() {

  var $dataName_2 = $(this).data("name");

  $('div.projContent').css('height', '0vh');

  setTimeout(function() {
    $("#" + $dataName_2).css('height', '100vh');
  }, 290);

});
#projectSection {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  padding: 1em;
  padding-top: 0;
  width: 45vw;
  min-height: 100%;
  overflow-y: scroll;
  overflow-x: hidden;
}

.proj {
  max-width: 40vw;
  color: #003c48;
  max-height: 100vh;
}

.projtog {
  text-align: left;
  transition: all 0.2s ease;
}

.projContent {
  max-width: 40vw;
  max-height: 57vh;
  overflow: scroll;
  transition: all ease-in-out 200ms;
  position: relative;
}

.projectImages {
  max-width: 40vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="proj">
  <h2 data-name="projectX" class="projtog"></h2>
  <h3></h3>
  <div class="projContent" id="projectX">
    <p></p>
    <img class="projectImages" src="">
  </div>
</div>

【问题讨论】:

  • 但是... .projContent 是 #projectX...
  • 哦,我想我明白了……您希望连续点击不会导致它隐藏和重新显示。在这种情况下......您需要某种条件来测试点击的是否是活动的。
  • 您可以在最后删除 projtog 类。这样事件就不会继续触发。您必须将事件稍微重写为:$('h2').on('click', '.projtog', function() {... 并添加 $(this).removeClass('projtong')

标签: javascript jquery html css custom-data-attribute


【解决方案1】:
$('div.projContent').hide();

$('h2.projtog').click(function() {
  $(this).nextAll(".projContent").toggle();
});

以上代码将切换projContent div。

【讨论】:

  • 您可以通过在页面加载时通过 CSS 隐藏 projContent div 来进一步改进它,例如 .projContent{display:none;}
猜你喜欢
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 2023-01-22
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
相关资源
最近更新 更多