问题
I'm trying to hide a div both when 1) certain other divs are clicked, and when 2) empty space on the margins of the page are clicked, space not contained by any div. I've got the first part covered, but I do not know how to do the second. I don't want the div to hide when ANYTHING outside the div is clicked. Just when empty space is clicked.
Here's a simple jsfiddle to play with.
And here's the basic jsquery I'm using. Can I add something that will make "text1" or "text2" disappear when the user clicks empty space?
$("#2").click(function() {
$('#text1').slideUp(300);
});
$("#1").click(function() {
$('#text2').slideUp(300);
});
回答1:
You can simply add a specific class to the div items that will be clicked and do this:
$(document).click(function (event) {//when anywhere is clicked on the page
if (!$(event.target).hasClass('MyClass')) {//if the clicked item has this class
$('#text2').slideUp(300);//hide
$('#text1').slideUp(300);//hide
}
});
DEMO: https://jsfiddle.net/tjrsvbuc/3/
回答2:
I found this beaufitul solution here on Stackoverflow:
$(document).mouseup(function (e)
{
var container = $("#text1, #text2");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.slideUp(300);
}
});
Updated Fiddle
回答3:
Hope this is you looking for add an event in javascript e.stopPropagation();
$(document).ready(function(){
$("#1").click(function(e){
e.stopPropagation();
$("#text1").slideDown(300);
});
});
$(document).ready(function(e){
$("#2").click(function(e){
e.stopPropagation();
$("#text2").slideDown(300);
});
});
$("#2").click(function() {
$('#text1').slideUp(300);
});
$("#1").click(function() {
$('#text2').slideUp(300);
});
$("body").click(function() {
$('#text1').slideUp(300);
$('#text2').slideUp(300);
});
来源:https://stackoverflow.com/questions/30190625/trigger-event-in-jsquery-when-clicking-on-empty-space-outside-of-any-div