jquery - 在鼠标悬停时显示搜索图标

标签 jquery css

我正在尝试当鼠标悬停在我的图像上时显示图标搜索,但我没有得到正确的结果。谁能帮忙?欢迎任何提示!

我的 html:

<article id="posts">
    <img class="search src="images/search.png"/>
    <img src="images/image1.jpg"  />
    <h2>Title 1</h2>
    <p>lorem ipsum 1</p>
</article>

我的 jQuery:

var search = $('<img src="path/to/search/icon.png" class="search" />');
$('.search').hover( function(){
    $(this).append(search);
});

最佳答案

这是一个纯 css 效果,你不需要 js 来实现结帐 css :hover

<article id="posts">
   <img class="search" src="http://lorempixel.com/400/200/food/1/" />
   <img src="http://lorempixel.com/400/200/food/2/" />
   <h2>Title 1</h2>
   <p>lorem ipsum 1</p>
</article>

CSS

#posts img:nth-of-type(2){display:none}
#posts:hover img.search{display:none}
#posts:hover img:nth-of-type(2){display:inline-block}

THE DEMO

或者这个

#posts img:nth-of-type(2){display:none}
#posts:hover img:nth-of-type(1){display:none}
#posts:hover img:nth-of-type(2){display:inline-block}

THE DEMO

或者这个

#posts img.search +img{display:none}
#posts:hover img.search{display:none}
#posts:hover img.search +img{display:inline-block}

THE DEMO

或者在class .Search之后的img中添加class .hover

<article id="posts">
   <img class="search" src="http://lorempixel.com/400/200/food/1/" />
   <img class="hover" src="http://lorempixel.com/400/200/food/2/" />
   <h2>Title 1</h2>
   <p>lorem ipsum 1</p>
</article>

CSS

#posts img.hover{display:none}
#posts:hover img.search{display:none}
#posts:hover img.hover{display:inline-block}

#posts .hover{display:none}
#posts:hover .search{display:none}
#posts:hover .hover{display:inline-block}

THE DEMO

最简单的方法是这样的:

#posts:not(:hover) img.hover{display:none}
#posts:hover img.search{display:none}

THE DEMO

你把它结合起来你有这样的东西:

#posts:not(:hover) img.hover,#posts:hover img.search{display:none}

或者这个:

#posts:not(:hover) .hover,#posts:hover .search{display:none}

THE DEMO

关于jquery - 在鼠标悬停时显示搜索图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22355108/

相关文章:

javascript - 我可以使用 AJAX 'POST' 将数据发布到服务器上的 JSON 文件吗?

javascript - 困惑: Ajax Framework vs JavaScript Framework?

jquery - 如何检查点击事件是否已经绑定(bind) - JQuery

javascript - JSFIDDLE 无法正常工作

javascript - Grails 资源、302、SSL 和 Chrome

javascript - Magento 2,链接无效,图像未加载

javascript - 在具有特定类的 div 中检查复选框的更改时运行 JavaScript 函数

javascript - Keydown/keyup 事件未检测到在 Chrome 中的输入文本字段上按下的 Escape 键

javascript - 切换到备用样式表时如何防止出现主样式表?

css - 如何在 spring MVC 应用程序中为不同的 URL 加载 CSS