单击链接时显示模态



我有这个链接,我想用id显示下面的模态"模态";当这个带有id"的链接时;showItem";被点击了,但我不知道如何实现。

你知道实现这一目标需要什么吗?

HTML链接:

<a href="#" id="showItem" class="block relative" >
<img alt="profil" src="images/img/1.jpg"
class="mx-auto object-cover rounded-full h-40 w-40 "/>
</a>

HTML模式:

<div id="modal"  class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
<div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div class="sm:flex sm:items-start">
<div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
</div>
<section>
<div class="py-20 bg-gray-50 radius-for-skewed">
<div class="container mx-auto px-4">
<div class="flex flex-wrap items-center -mx-3">
<div class="w-full lg:w-1/3 px-3 mb-8 lg:mb-0">
<ul class="flex flex-wrap flex-row lg:flex-col justify-center lg:justify-start space-x-6 lg:space-x-0">
<li>
<button class="text-2xl lg:text-4xl mb-4 text-gray-300 hover:text-gray-400 font-bold">Item 1
</button>
</li>
<li>
<button class="text-2xl lg:text-4xl mb-4 text-gray-300 hover:text-gray-400 font-bold">Item 2
</button>
</li>
<li>
<button class="text-2xl lg:text-4xl mb-4 text-gray-900 font-bold">Item 1</button>
</li>
<li>
<button class="text-2xl lg:text-4xl mb-4 text-gray-300 hover:text-gray-400 font-bold">Item 5
</button>
</li>
</ul>
</div>
<div class="w-full lg:w-2/3 px-3">
<div class="flex p-6 flex-wrap bg-white rounded-lg shadow">
<div class="w-full lg:w-1/2 lg:pl-3 lg:mt-6 order-first lg:order-last">
<h4 class="text-2xl font-bold font-heading">Item 1</h4>
<p class="mb-6 text-gray-500">Desc</p>
<p class="mb-6 text-gray-500 leading-loose">Desc3</p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
</div>

只需将onclick属性添加到链接中,并调用一个JavaScript函数来显示模态并返回false以防止浏览器调用url。

<a href="#" id="showItem" class="block relative" onclick="showModal(); return false;">

现在使用display属性在CSS中隐藏模态。

#modal {
display: none;
/* your custom styles */
}

添加另一个具有活动类的样式。所以模态只有在激活时才会弹出。

#modal.active {
display: block;
}

现在,在JavaScript中,当单击链接时,将活动类添加到modal。

const showItemBtn = document.getElementById('showItem');
const modal = document.getElementById('modal');
function showModal() {
modal.classList.add('active');
}

仅此而已。

最新更新