通过按钮切换类的jQuery弹出窗口

时间:2019-02-14 16:50:16

标签: javascript jquery html

嗨,我有一个带有active class的模态弹出窗口,一旦此类出现在模态上,一旦此类消失,它就会消失。我希望能够按下一个按钮,并且出现模态,并且模态中的关闭按钮会关闭模态。我正在使用JQuery,因此到目前为止我已经尝试过:

jQuery

  <script>
        $(document).ready(function(){
            $("button").click(function(){
                $(".modal").addClass(".active");
            });
        }); 
    </script>

HTML

<button>Modal</button>

无效的模式HTML

<div class="modal" id="modal-id">
</div>

有效模式HTML

<div class="modal active" id="modal-id">
</div>

4 个答案:

答案 0 :(得分:2)

您无需在类名前使用点号:

<script>
    $(document).ready(function(){
        $("button").click(function(){
            $(".modal").addClass("active");
        });
    }); 
</script>

答案 1 :(得分:0)

您将需要两个click函数。一种附加在显示模式的按钮上,另一种附加在用于关闭模式的按钮上。

    $(document).ready(function(){

    // Button that opens the modal
        $("#open-button").click(function(){
            $(".modal").addClass("active");
        });
    }); 

    // Button on the modal that closes the modal
        $("#close-button").click(function(){
            $(".modal").removeClass("active");
        });
    }); 
  }); 

答案 2 :(得分:0)

您还需要在弹出窗口上有一个按钮。连同代码一起,添加弹出html并在关闭按钮上添加额外的click事件。

$('#show-popup').on('click', function(){
      $('.modal').addClass('active');
    });


$('#close-popup').on('click', function(){
  $('.modal').removeClass('active');
});
.modal {
  display: none;
  position: relative;
  border: 1px solid red;
  width: 500px;
  height: 250px;
}

.modal.active {
  display: block;
}

#close-popup {
  position: absolute;
  top: -20px;
  right: -20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="show-popup">Show</button>

<div class="modal" id="modal-id">
  <button id="close-popup">X</button>
</div>

答案 3 :(得分:0)

如前所述,影响class属性的方法不需要toggleClass,它不是选择器,而是期望的字符串类名称。

要在每次单击按钮时显示/隐藏模态,可以使用addClass而不是$(document).ready(function(){ $("button").click(function(){ $(".modal").toggleClass("active"); }); });

.modal{
 display:none;
 border:solid 1px black;
 width:300px;
 height:300px;
}

.modal.active{
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Modal</button>

<div class="modal" id="modal-id">
modal
</div>
a