Về cơ bản, bạn' d trước tiên phải đo lường chế độ xem dimentio ns, bằng cách sử dụng đối tượng cửa sổ, sau đó bạn cần phải lặp qua từng phần tử mà bạn muốn kiểm tra và tính toán thời gian phù hợp.
Xem ví dụ này jsfiddle để biết ví dụ.
Dưới đây là đoạn code (vì hậu thế của):
HTML:
<div id="info">
<p class="wxh"></p>
<p class="txl"></p>
<p class="report"></p>
</div>
<h1>A big list!</h1>
<ul></ul>
CSS:
#info{
position: fixed;
right: 0px;
text-align: center;
background: white;
border: 2px solid black;
padding: 10px;
}
JS:
$(function(){
$(window).bind('scroll.measure resize.measure',function(){
// Gather together the window width, height, and scroll position.
var winWidth = $(window).width(),
winHeight = $(window).height(),
winLeft = $(window).scrollLeft(),
winTop = $(window).scrollTop(),
winBottom = winTop + winHeight,
winRight = winLeft + winWidth,
inView = [];
// Loop over each of the elements you want to check
$('.inview').each(function(){
// Get the elements position and dimentions.
var pos = $(this).position(),
width = $(this).outerWidth(),
height = $(this).outerHeight();
// Set bottom and right dimentions.
pos.bottom = pos.top + height;
pos.right = pos.left + width;
// Check whether this element is partially within
// the window's visible area.
if((
pos.left >= winLeft &&
pos.top >= winTop &&
pos.right <= winRight &&
pos.bottom <= winBottom
) || (
pos.left >= winLeft && pos.top >= winTop &&
pos.left <= winRight && pos.top <= winBottom
) || (
pos.right <= winRight && pos.bottom <= winBottom &&
pos.right >= winLeft && pos.bottom >= winTop
)){
// Change this to push the actual element if you need it.
inView.push($(this).text());
}
});
// For the purposes of this example, we only need the
// first and last element, but in your application you may need all.
var first = inView.shift(),
last = inView.pop();
// Show the details in the info box.
$('#info .wxh').text(winWidth+' x '+winHeight);
$('#info .txl').text(winTop+' x '+winLeft);
$('#info .report').text('Showing from '+first+' to '+last);
});
// The rest is just setup stuff, to make the area scrollable.
for(var i=0; i<100; i++){
$('ul').append('<li class="inview">List item '+i+'</li>');
}
$(window).trigger('resize.measure');
})
Nguồn
2012-02-14 05:01:56
Bạn có thể kiểm tra [http: // stackoverflow.com/questions/704758/how-to-check-if-an-element-là-thực-nhìn thấy-với-javascript] (http://stackoverflow.com/questions/704758/how-to-check-if-an -element-is-really-visible-with-javascript) cho các câu trả lời cho một câu hỏi tương tự. – Bill