修改脚本以关闭 Div

Modify Script to Close Div

我有一个不错的小节目,一次只有一个 div 我在以下位置找到的脚本可以正常工作: Random Snippets(第二个演示)看起来像这样:

function showonlyone(thechosenone) {
     $('.newboxes').each(function(index) {
          if ($(this).attr("id") == thechosenone) {
               $(this).show(200);
          }
          else {
               $(this).hide(600);
          }
     });
}

它唯一不会做的是在打开后关闭 div。目前我将两个 div 都设置为显示:none 并希望让用户可以选择在他们完成查看后关闭它们。

知道如何修改吗?

您可以有一个单击事件,在单击时关闭它们:

$('.newboxes').click( function() {
    $(this).hide(600);
});

if 语句中添加关于当前项目可见性的条件:

function showonlyone(thechosenone) {
     $('.newboxes').each(function(index) {
          if ($(this).attr("id") == thechosenone && $(this).css("display") == "none") {
               $(this).show(200);
          }
          else {
               $(this).hide(600);
          }
     });
}

您必须向用户提供一个按钮或其他东西来关闭 divs。假设每个 div:

里面都有一个这样的按钮

HTML

<div class="div-class">
    <p>Box content</p>
    <button class="close">Close</button>
</div>

jQuery

$('.close').on('click', function() {
   $(this).closest('.div-class').hide();
});