我在加载页面上有一个引导模式,它可以正常工作,但我想在一个元素中添加类,如果它处于活动状态,如果它不活动则将其删除我尝试了以下但它无法正常工作! here is the example
$(window).load(function() {
$("#myModal").modal("show");
});
if ($("#myModal").hasClass("in")) {
$(".test").addClass("active");
} else {
$(".test").removeClass("active");
}
.test {
width: 100px;
height: 100px;
background-color:#e0e0e0;
}
.active {
background-color:#000;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="test"></div>
答案 0 :(得分:1)
使用shown.bs.modal
和hidden.bs.modal
检测模态是否已打开,然后add
或remove
类。
$(window).load(function() {
$("#myModal").modal("show");
});
$('#myModal').on('shown.bs.modal', function() {
$(".test").addClass("active");
console.log('Active');
}).on('hidden.bs.modal', function() {
$(".test").removeClass("active");
console.log('Not Active');
});
&#13;
.test {
width: 100px;
height: 100px;
background-color: #e0e0e0;
}
.active {
background-color: #000;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="test"></div>
&#13;