我有一列图像,我想根据滚动位置添加一个计数器来显示当前哪一个是主要的。
这是fiddle
<div class="counter">1/7<br>(the number before the "/" needs to be dynamic, I can get the total)</div>
<div class="image-wrapper">
<img class="image" src="http://via.placeholder.com/350x350" alt="">
<img class="image" src="http://via.placeholder.com/350x350" alt="">
<img class="image" src="http://via.placeholder.com/350x350" alt="">
<img class="image" src="http://via.placeholder.com/350x350" alt="">
<img class="image" src="http://via.placeholder.com/350x350" alt="">
<img class="image" src="http://via.placeholder.com/350x350" alt="">
<img class="image" src="http://via.placeholder.com/350x350" alt="">
</div>
.counter {
position: fixed;
top: 50%;
}
谢谢!
答案 0 :(得分:0)
如果我理解了您的问题,那么您正尝试更新X / 7
中的变量X,指示当前可见的图像。鉴于您当前的HTML,请尝试以下方法:
$.fn.isInViewport = function(excludePartials) {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
if (excludePartials) {
var bottomVisible = (elementBottom - viewportTop) / $(this).outerHeight();
var isInView = elementBottom > viewportTop && elementTop < viewportBottom;
return isInView && bottomVisible > 0.5; // false if its less than 50% visible
}
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).on('resize scroll', function() {
// new array to store all images in view
var imagesInView = new Array();
$('.image').each(function() {
// pass in false if partially visible objects should be used
if ($(this).isInViewport(true)) {
var i = $(".image").index( $(this) );
imagesInView.push(i);
}
// get the earliest viewable image:
$("#active").text( imagesInView[0] + 1 );
});
});
&#13;
.counter {
position: fixed;
top: 50%;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="counter"><span id='active'>1</span>/7<br>(the number before the "/" needs to be dynamic, I can get the total)</div>
<div class="image-wrapper">
<img class="image" src="//via.placeholder.com/350x350" alt="">
<img class="image" src="//via.placeholder.com/350x350" alt="">
<img class="image" src="//via.placeholder.com/350x350" alt="">
<img class="image" src="//via.placeholder.com/350x350" alt="">
<img class="image" src="//via.placeholder.com/350x350" alt="">
<img class="image" src="//via.placeholder.com/350x350" alt="">
<img class="image" src="//via.placeholder.com/350x350" alt="">
</div>
&#13;
您可以通过阅读注释并相应地调整变量来播放容差或禁用部分可见元素。
我在这里找到了isInViewport
代码段:https://medium.com/talk-like/detecting-if-an-element-is-in-the-viewport-jquery-a6a4405a3ea2