jQuery: Toggle Class on Click, Remove if Outside Element
You can achieve this functionality using the click event and the closest and hasClass methods in jQuery. Here's an example:
$(document).click(function(e) {
var target = $(e.target);
// Check if the clicked element is not closest to the class 'addclass'
if (!target.closest('.addclass').length && !target.hasClass('addclass')) {
// Remove the class 'addclass'
$('.addclass').removeClass('addclass');
}
});
$('.addclass').click(function() {
// Add the class 'addclass'
$(this).addClass('addclass');
});
In this code, when the user clicks anywhere on the document, it checks if the clicked element is not the closest or does not have the class 'addclass'. If it's true, it removes the class 'addclass' from all elements with that class.
On the other hand, when the user clicks on an element with the class 'addclass', it adds the class to that specific element.
原文地址: https://www.cveoy.top/t/topic/qosA 著作权归作者所有。请勿转载和采集!