我遇到了一个问题,如果模态被包装在标签中,它就不会触发。 在我的示例中,如果您单击链接的"正常"字体样式部分,它会正确触发,如果您单击斜体所在的位置,它不会。
有什么想法吗?
.JS
$(function () {
const openModals = [];
$('.modal-button').click(e => {
e.preventDefault();
$(e.target).closest('.modal').add('body').addClass('open');
openModals.push($($(e.target).attr('href')).show());
});
$(window).add('.close').click(e => {
e.stopPropagation();
if ($(e.target).is('.modal, .close')) {
const closing = openModals.pop().addClass('modal-content-active');
setTimeout(() => {closing.hide().removeClass('modal-content-active')}, 0);
if (openModals.length > 0) {
openModals[openModals.length - 1].removeClass('open');
} else $('body').removeClass('open');
}
});
});
小提琴
在第一个事件处理程序中,您引用的是"目标"而不是"当前目标">
e.target
表示正在单击的确切元素(在本例中为<em/>
(,而e.currentTarget
表示事件处理程序附加到的元素,即href
值所在的位置。
我将第一个事件处理程序中对e.target
的两个引用更改为e.currentTarget
,并且事情应该按预期工作。
$('.modal-button').click(e => {
e.preventDefault();
$(e.currentTarget).closest('.modal').add('body').addClass('open');
openModals.push($($(e.currentTarget).attr('href')).show());
});
https://jsfiddle.net/q7o6f9su/
https://jsfiddle.net/qLpcfx8k/您只需要将相同的 href 传递给标签并:)
<a href="#myModal1" class="modal-button">This is the trigger <em href="#myModal1"> for the first modal</em></a><br>
<a href="#myModal3" class="modal-button">This is the trigger <em href="#myModal1"> for the second modal</em></a>