highlight element that is closest to middle of vie

2019-07-26 20:10发布

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.

How would I do this?

I'm already using the InView and ViewportOffset plugins.

标签: jquery
1条回答
我命由我不由天
2楼-- · 2019-07-26 20:41

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");
查看更多
登录 后发表回答