jQuery closest();
I'm trying to animate an image which is partly hidden (via overflow: hidden) inside a list item. I want this to happen when a user hovers over an A tag inside the same list item.
I have the following markup:
<div id="projects" class="section">
<ul>
<li>
<img src="assets/img/projects/pf6.jpg" widt开发者_开发技巧h="980" height="500" alt="Project title" />
<h2 class="left middle"><span>new</span><a href="#">Title 1</a></h2>
</li>
<li>
<img src="assets/img/projects/pf4.jpg" width="980" height="500" alt="Project title" />
<h2 class="bottom right"><a href="#">Title 2</a></h2>
</li>
</ul>
</div>
My basic css:
#projects ul li {
width: 100%;
height: 450px;
position: relative;
display: block;
margin-bottom: 20px;
color: #fff;
overflow: hidden;
}
#projects ul li img {
position: absolute;
top: -50px;
left: 0;
}
I am trying the following with jQuery to move the image (to no avail):
$("#projects li h2 a").hover(
function () {
$(this).closest("img").animate({paddingTop: "50px"}, "slow");
},
function () {
$(this).closest("img").animate({paddingTop: "0"}, "slow");
}
);
Anyone have any idea why this is not working! - any help much appreciated :-)
I think it should be:
$(this).closest("li").children("img").animate()
Or you could do:
$(this).closest("h2").prevAll("img")
closest()
only selects the current element and its parent elements (and then limits it to the first match).
Your img
element isn't a parent of the link you have the hover handler on, therefore it doesn't work.
Update: as ScottyUSCD pointed out, the previous code I posted won't work. I misread the source and thought the elements were siblings.
His answer was correct:
$(this).closest("li").children("img")
This will navigate up to the closest parent li
element, then look through that element's children for any img
elements.
If the <img>
could also be after the <h2>
, use:
$(this).closest("h2").siblings("img");
精彩评论