提问人:JJBeaudry 提问时间:3/16/2022 更新时间:3/16/2022 访问量:96
在jquery中设置每个元素的样式
Set style of each element in jquery
问:
我有以下代码将所有未悬停的元素的不透明度设置为 0.5。
const handleHover = function (e) {
if ($(e.target).hasClass("nav_link")) {
const siblings = e.target.closest("nav").querySelectorAll(".nav_link");
siblings.forEach((el) => {
if (el !== e.target) el.style.opacity = this;
});
}
};
$(".nav").on("mouseover", handleHover.bind(0.5));
$(".nav").on("mouseout", handleHover.bind(1));
我的问题是如何使用jQuery方法而不是使用querySelectorAll在兄弟姐妹上编写forEach循环?
答:
3赞
Phil
3/16/2022
#1
为此,我根本不会使用JavaScript或jQuery。
使用 CSS,您可以定位悬停在悬停状态内但本身未悬停的所有元素。.nav_link
nav
.nav_link {
transition: opacity .1s;
cursor: pointer;
}
nav:hover .nav_link:not(:hover) {
opacity: .5;
}
<nav>
<ul>
<li class="nav_link">Link #1</li>
<li class="nav_link">Link #2</li>
<li class="nav_link">Link #3</li>
<li class="nav_link">Link #4</li>
</ul>
</nav>
为了完整起见,这里是一个jQuery版本
// Delegated hover in / out event handler
$("nav").on("mouseenter mouseleave", ".nav_link", e => {
$(e.delegateTarget) // start at "<nav>"
.find(".nav_link") // find all the links
.not(e.target) // except the hovered one
.toggleClass("fade"); // toggle the "fade" class
});
.nav_link { cursor: pointer; transition: opacity .1s; }
.fade { opacity: .5; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script><nav><ul><li class="nav_link">Link #1</li><li class="nav_link">Link #2</li><li class="nav_link">Link #3</li><li class="nav_link">Link #4</li></ul></nav>
评论