javascript - 如何在使用 JS 或 Jquery 悬停时向相应的 div 容器显示文本?
问题描述
当鼠标悬停在 div 属性上时,我试图显示文本。我在每个框中有三个 div 框和三个文本。我知道我只能通过 CSS 来完成这项工作,但我是编码新手,并且正在尝试更好地学习 JS 和 Jquery。
我一开始是用纯 JS 练习的,我只能在悬停时显示第一个框,但不能显示其他两个,当我将变量打印到控制台时,我注意到它只是拉动了 div 的第一个元素,那时我切换到 .querySelectorAll 以获取所有三个元素,但现在我不知道如何使用 this/event.target/event.currentTarget。我假设这就是我用来显示目标元素的方法,但我不知道如何使用它们。
let text = document.querySelectorAll('a div');
let pic = document.querySelectorAll('.boxcontainer a')
pic.addEventListener("mouseenter", function() {
this.style.visibility = 'visible';
});
pic.addEventListener("mouseleave", function() {
this.style.visibility = 'hidden';
});
.boxcontainer {
width: 30%;
height: 50%;
position: fixed;
display: flex;
flex-direction: column;
z-index: 100;
}
.boxcontainer a {
box-shadow: -9px 12px 7px 0px rgba(0, 0, 0, 0.336);
margin: 10px;
padding-top: 10%;
padding-bottom: 10%;
text-decoration: none;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
.boxcontainer a:hover {
transform: scale(1.1);
color: white;
}
#text {
visibility: hidden;
}
<div class="boxcontainer">
<a href="asia.html" style="background-color:#46515a;">
<div id='text'>asia.</div>
</a>
<a href="americas.html" style="background-color: #2d343a;">
<div id='text'>americas.</div>
</a>
<a href="europe.html" style="background-color: #1a1f22;">
<div id='text'>europe.</div>
</a>
</div>
解决方案
我得到了答案,感谢任何帮助过的人
jQuery
$('.text').hide();
$(".boxcontainer a").on('mouseenter', function() {
$(this).find('.text').fadeIn(300);
});
$(".boxcontainer a").on('mouseleave',function() {
$(this).find('.text').hide();
});
HTML
<div class="boxcontainer">
<a href="asia.html" style="background-color:#46515a;"> <div class = 'text'>asia.</div></a>
<a href="americas.html" style="background-color: #2d343a;"> <div class='text'>americas.</div></a>
<a href="europe.html" style="background-color: #1a1f22;"><div class='text'>europe.</div></a>
</div>
CSS
.boxcontainer{
width: 30%;
height: 50%;
position: fixed;
display: flex;
flex-direction: column;
z-index: 100;
}
.boxcontainer a{
box-shadow: -9px 12px 7px 0px rgba(0, 0, 0, 0.336);
margin: 10px;
padding-top: 10%;
padding-bottom: 10%;
text-decoration: none;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
.boxcontainer a:hover{
transform: scale(1.1);
color: white;
}
推荐阅读
- google-cloud-platform - 在创建 VM 期间出现许可错误
- prometheus - Prometheus PromQL 外连接
- flutter - Flutter:NoSuchMethodError:参数不匹配的闭包调用:函数'Global.models。
' - python - 如何让 pylint 使用 init-hook 正确导入我的文件
- ruby - Gem::Specification:Class 的未定义方法 `stubs_for' (NoMethodError)
- json - 删除对象时的 URL 是什么
- node.js - 帖子文件已删除,但仍在 gatsby develop 上提供
- bash - Unix Shell - 为什么重复相同的 $RANDOM 数字?
- javascript - 如何将 tail.select 列表重置为默认值?
- python - ModuleNotFoundError - 无法在 Mac 上为 Python 3 安装 OpenCV