问题描述
一个简单的问题,我有一个无序的产品"列表,我希望描述出现在悬停上.除将动画一次应用于每个单个产品外,这可以正常工作.如何只针对我徘徊的列表项而不给每个li提供唯一的ID?我确定答案使用的是"this",但我还没有弄清楚如何成功做到这一点.
Quick question, I have an unordered list of "products" and I want the description to appear on a hover. This works fine, except the animation is applied to every single product at once. How do I target just the list item I'm hovering on without giving a unique ID to every single li? I'm sure the answer uses "this" but I haven't figured out how to do it successfully.
产品:
<ul id='products'>
<li>
<div class='productDesc'>
<img src = 'images/myImage1' />
<p>
Description 1...
</p>
</div>
</li>
<li>
<div class='productDesc'>
<img src = 'images/myImage2' />
<p>
Description 2...
</p>
</div>
</li>
</ul>
javascript:
javascript:
$(document).ready(function() {
$('#products li').hover(function(){
$(".productDesc").fadeIn("slow");
}, function(){
$(".productDesc").fadeOut("slow");
});
});
CSS:
.productDesc{ display:none; }
推荐答案
您需要使用$(this)
来获取对悬停列表项的引用以及 .find() ,以将子.productDesc
放在该悬停的列表项中:
You need to use $(this)
to get a reference to the hovered list item along with .find() to get the child .productDesc
inside that hovered list item:
$(document).ready(function() {
$('#products li').hover(function(){
$(this).find(".productDesc").fadeIn("slow");
}, function(){
$(this).find(".productDesc").fadeOut("slow");
});
});
Fiddle Demo
您还可以使用 .fadeToggle() 缩短代码在fadeIn
和fadeOut
$(document).ready(function() {
$('#products li').hover(function(){
$(this).find(".productDesc").fadeToggle("slow");
});
});
Fiddle Demo
这篇关于定位单个< li>在< ul>之内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!