We have a scrollable div that has CSS hieght:40px;
. Inside it are multiple LI height:20px
<div id="#scroller">
<li title="I1">item1</li>
<li title="I2">item2</li>
<li title="I3">item3</li>
<li title="I4">item4</li>
<li title="I5">item5</li>
<li title="I6">item6</li>
<li title="I7">item7</li>
<li title="I8">item8</li>
<li title="I9">item9</li>
</div>
When 开发者_StackOverflow社区the user scrolls I want to trigger a script that determines the first of the two elements which is visible. The div scroll is designed to snap to elements. So if you scroll down and item3 and item 4 are visible how do I fund out that item 3 is the top visible element.
I tried $('#scroller li:visible')
but this does not work as far as the div is concerned they are all visible just hidden behind their container.
Any ideas,
Marvellous
Update
Updated with a working example http://jsfiddle.net/U4qyp/32/
I think .position()
should do the job. It gives you the position of the element relative to its parent element. After you called .position() you can access the element coordinates using the properties top
and left
.
http://api.jquery.com/position/
The element whose top position plus its height is major than zero, is visible.
Here is an example of what I mean.
http://jsfiddle.net/U4qyp/10/
I'd have thought the best way to do it is in your scroll event capture the scrollTop value of the div and compare it to the top of each li element (maybe add the height so you can see if the element is completely out of view).
jQuery's position
method gets the position relative to the container, and you can get the top position by doing $("li").position().top;
So my solution was to write a loop to go through all the elements and find the one with the smallest value for position().top
and pick that out. Here's the script I wrote:
$(function() {
var mostVisibleItem = $("li:first");
var smallestOffset = mostVisibleItem.position().top;
$("li").each(function(i, item) {
if($(item).position().top < smallestOffset)
{
smallestOffset = $(item).position().top;
mostVisibleItem = $(item);
}
});
mostVisibleItem.css("color", "red");
});
You can see this working in JSFiddle here: http://jsfiddle.net/P69y2/
Hope this helps :)
Something like this would work, where you would replace the console.log with your display logic.
<script>
$(function() {
$('#scroller').scroll(function() {
$('#scroller li').each(function() {
if ($(this).position().top > 0) {
console.log($(this).html());
return false; // break once the first displayable value has been returned.
}
})
})
})
</script>
精彩评论