我在 wordpress 工作,试图弄清楚如何在悬停远程图像时更改侧导航元素的 css 颜色。
我本来可以使用 CSS 轻松完成此操作,只需为每个元素分配 CSS 悬停类,但由于这是一个 CMS,导航和图片库将动态变化。
因此,我正在寻找有关如何完成此操作的 JQuery。有什么建议吗?
这是 html 的示例:
<div class="imgGallery">
<img class="page-item-54" src="/image1.jpg">
<img class="page-item-66" src="/image2.jpg">
<div>
当有人将鼠标悬停在上面的特定图像上时,它会更改下面图像的 css:
<ul class="pageNav">
<li class="page-item-54">Sub Gallery 1</li>
<li class="page-item-66">Sub Gallery 2</li>
</ul>
谢谢! 特洛伊
最佳答案
您可以使用 jQuery hover
为图像的 mouseenter
和 mouseleave
事件连接处理程序的函数(jQuery 会很乐意在不支持它们的浏览器上模拟):
$(".imgGallery img").hover(
function() {
// Code for when the hover starts, the (raw) hovered `img`
// element is `this`, from which we can get the class name
// to feed into a selector for finding the relevant `li`
$(".pageNav ." + this.className).css(/* your change here */);
},
function() {
// Code for when the hover ends, the (raw) unhovered `img`
// element is `this`
$(".pageNav ." + this.className).css(/* your change here */);
}
);
这是一个使用 just one pageNav
的实例, 和 a revision with multiple pageNavs
只是为了表明它正在同时更新多个位置。
mouseenter
和 mouseleave
(许多浏览器仍然不支持 IE 创新,但如果缺少 jQuery 会提供)使用起来要容易得多这种事情比 mouseover
和 mouseout
更重要,因为 mouseover
和 mouseout
会冒泡。 (在您的情况下,这可能无关紧要,因为您使用的是 img
;但是,如果您使用的元素可能具有子元素,那将产生很大的不同。)
关于javascript - 悬停时在多个位置更改 CSS(需要 jquery 解决方案),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3142609/