在jQuery中使元素更靠近屏幕中间 [英] Get the element closer to the middle of the screen in jQuery

查看:72
本文介绍了在jQuery中使元素更靠近屏幕中间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面中有一个项目div列表.

I have a list of item divs in the page.

示例:

<div data-page='1' class'item' ></div>
<div data-page='1' class'item' ></div>
<div data-page='1' class'item' ></div>
<div data-page='2' class'item' ></div>
<div data-page='2' class'item' ></div>
<div data-page='2' class'item' ></div>
<div data-page='3' class'item' ></div>
<div data-page='3' class'item' ></div>
<div data-page='3' class'item' ></div>

我需要找出屏幕最中央部分的元素并获取其data-page号.

I need to find out the element that is in the most center part of the screen and get its data-page number.

如果所有div都靠近页面的按钮或由于其在页面下方而不可见,则我会获得最高级的div,因为它离中间位置更近,并且如果所有div都在中间上方或不可见,是因为它们位于可见视图之外的窗口的上部,因为它离中间位置更近,所以我获得了最底部的div.

If all the div are close to the button of the page or not visible because its down the page, I get the top most one because it's closer to the middle, and if all the div are above the middle or not visible because they are at the upper part of the window outside the visible view, I get the bottom most div because it's closer to the middle.

我尝试过的操作(

上述功能对我不起作用,因为它以红色突出显示了最底部的一个元素.

The above function didn't work for me, because it highlighted in red a bottom most element.

如何在jQuery中做到这一点,并在垂直滚动页面时不断报告最接近的那个.

How can I do that in jQuery and also continuously report the closest one as I vertically scroll the page.

推荐答案

在滚动事件上,您可以获取屏幕中央,然后循环查看要检查的元素,并获取每个元素的位置并找出最接近的元素到屏幕中间

On the scroll event, you can get the middle of the sreen and then loop the elements you want to check and get each of their positions and find which is closest to the middle of the screen

 $(function(){
    $(window).scroll(function(){        
        // get the scroll position of the document + half the window height
        var scrollTop = $(document).scrollTop() + ($(window).height() / 2);
        var positions = [];

        // push each of the items we want to check against to an array with their position and selector
        $('.item').each(function(){
            $(this).removeClass("active");
            positions.push({position:$(this).position().top, element: $(this)});
        });

        var getClosest = closest(positions,scrollTop);
        getClosest.addClass("active"); // the element closest to the middle of the screen
        console.log( getClosest.attr("data-page") );
    });

    // finds the nearest position (from an array of objects) to the specified number
    function closest(array, number) {
        var num = 0;
        for (var i = array.length - 1; i >= 0; i--) {
            if(Math.abs(number - array[i].position) < Math.abs(number - array[num].position)){
                num = i;
            }
        }
        return array[num].element;
    }        
});

这是一个工作示例

这篇关于在jQuery中使元素更靠近屏幕中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆