最靠近视口中间的突出显示元素 [英] highlight element that is closest to middle of viewport

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

问题描述

我在页面上有3个锚点.我想突出显示一个固定的按钮列表,具体取决于哪个锚点最靠近视口的中间.

I have 3 anchors on the page. I want to highlight a list of buttons that are fixed depending on which anchor is closest to the middle of the viewport.

我该怎么做?

我已经在使用InView和ViewportOffset插件.

I'm already using the InView and ViewportOffset plugins.

推荐答案

因此,如果不执行视口的坐标,则可以得到中间值:

so if you do no the viewport's coordinates, then, you can get the middle:

x = (viewport.x2 - viewport.x1) / 2;
y = (viewport.y2 - viewport.y1) / 2;

现在您可以执行以下操作:

now you do something like:

var distances = [];
var elems = $("a");
elems.each(function(i){
    var o = $(this).offset();
    var d2 = (o.left - x)*(o.left - x) + (o.top - y)*(o.top - y);
    distances[i] = d2
});

现在您有了数组中距离的平方",您需要搜索最小的(最接近中间的):

now you have the "square" of the distances in the array, you need to search for the smallest (closest to the middle):

var closest = 0;
for (i=0; i<distances.length;i++) {
    if (distances[i] < distances[closest]) {
         closest = i;
    }
}

现在您拥有最接近"元素中最接近元素的索引,因此您可以使用它进行任何操作,例如:

now you have the index of the closest element in "closest" so you can do anything with it like:

elems[i].addClass("higlighted");

这篇关于最靠近视口中间的突出显示元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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