我正在使用这段代码:
$('body').click(function() {
$('.form_wrapper').hide();
});
$('.form_wrapper').click(function(event){
event.stopPropagation();
});
这个HTML:
<div class="form_wrapper">
<a class="agree" href="javascript:;">I Agree</a>
<a class="disagree" href="javascript:;">Disagree</a>
</div>
问题是,我有链接在div和当他们不再工作时,点击。
$(document).ready(function() {
$('.modal-container').on('click', function(e) {
if(e.target == $(this)[0]) {
$(this).removeClass('active'); // or hide()
}
});
});
.modal-container {
display: none;
justify-content: center;
align-items: center;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
z-index: 999;
}
.modal-container.active {
display: flex;
}
.modal {
width: 50%;
height: auto;
margin: 20px;
padding: 20px;
background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-container active">
<div class="modal">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ac varius purus. Ut consectetur viverra nibh nec maximus. Nam luctus ligula quis arcu accumsan euismod. Pellentesque imperdiet volutpat mi et cursus. Sed consectetur sed tellus ut finibus. Suspendisse porttitor laoreet lobortis. Nam ut blandit metus, ut interdum purus.</p>
</div>
</div>
摘自https://sdtuts.com/click-on-not-specified-element/
现场演示http://demos.sdtuts.com/click-on-specified-element
$(document).ready(function () {
var is_specified_clicked;
$(".specified_element").click(function () {
is_specified_clicked = true;
setTimeout(function () {
is_specified_clicked = false;
}, 200);
})
$("*").click(function () {
if (is_specified_clicked == true) {
//WRITE CODE HERE FOR CLICKED ON OTHER ELEMENTS
$(".event_result").text("you were clicked on specified element");
} else {
//WRITE CODE HERE FOR SPECIFIED ELEMENT CLICKED
$(".event_result").text("you were clicked not on specified element");
}
})
})
您可以将tabindex设置为父元素<div>,而不是监听DOM上的每一次单击以隐藏一个特定的元素,并监听focusout事件。
设置tabindex将确保在<div>上触发模糊事件(通常不会)。
所以你的HTML看起来是这样的:
<div class="form_wrapper" tabindex="0">
<a class="agree" href="javascript:;">I Agree</a>
<a class="disagree" href="javascript:;">Disagree</a>
</div>
你的JS:
$('.form_wrapper').on('focusout', function(event){
$('.form_wrapper').hide();
});