我正在寻找使用 jQuery 实现此目的的最佳方法:当我将鼠标悬停在链接上时,它旁边会显示一个 div。当我停止悬停后它又被隐藏了。如果我单击该链接,div 将保持不变,直到再次单击。
这对我来说似乎是一个自然的解决方案,但我是 jQuery 的新手,希望得到建议:将 link.hover 和 link.click 连接到执行上述操作的逻辑,将“已单击” bool 值存储为数据链接上的属性。
这是一个好的方法,还是迂回的方法?
最佳答案
这是我认为您正在寻找的示例。当您将鼠标悬停在 a
上时显示/隐藏 div
,并在单击 a
时保持 div
可见.
$(document).ready(() => {
$("#thelink").on('mouseover', () => {
// Change state if the link hasn't been clicked, otherwise do nothing
if ($('#thelink').data("clicked") == false) {
$("#thediv").show();
}
});
$("#thelink").on('mouseout', () => {
// Change state if the link hasn't been clicked, otherwise do nothing
if ($('#thelink').data("clicked") == false) {
$("#thediv").hide();
}
});
$("#thelink").on('click', () => {
$("#thelink").data("clicked", true);
$("#thediv").show();
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="thelink" href="javascript:void(0)" data-clicked="false">The link</a>
<div hidden id="thediv">I am usually hidden. Mouse over the link to see me. Click on it and I'll stay visible.</div>
顺便说一句,这一切都可以使用 vanilla js 轻松完成。我喜欢向人们展示,现在很多事情都不需要 jQuery,所以对于 vanilla js 来说也是如此:
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('thelink').addEventListener('mouseover', () => {
const linkClicked = JSON.parse(document.getElementById('thelink').dataset['clicked']);
if(linkClicked == false) {
document.getElementById('thediv').hidden = false;
}
});
document.getElementById('thelink').addEventListener('mouseout', () => {
const linkClicked = JSON.parse(document.getElementById('thelink').dataset['clicked']);
if(linkClicked == false) {
document.getElementById('thediv').hidden = true;
}
});
document.getElementById('thelink').addEventListener('click', () => {
document.getElementById('thelink').dataset['clicked'] = true;
document.getElementById('thediv').hidden = false;
});
})
<a id="thelink" href="javascript:void(0)" data-clicked="false">The link</a>
<div hidden id="thediv">I am usually hidden. Mouse over the link to see me. Click on it and I'll stay visible.</div>
当然,有点详细,但您不依赖于外部库。如果 jQuery
让您的生活更轻松,请务必使用它,但请至少考虑一下您是否真的需要它。
关于jquery - div 的状态存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59966829/