使用jQuery坐标/偏移值将焦点设置在元素上

时间:2018-10-23 14:43:16

标签: javascript jquery

jQuery.fn.getCoord = function(){
    var elem = $(this);
    var x = elem.offset().left;
    var y = elem.offset().top;
    console.log('x: ' + x + ' y: ' + y);

    return {
        x,
        y
    };

};

以上函数可用于扩展jQuery,它返回一个对象,该对象具有给定元素的x和y坐标,分别为left和top值。

是否有一种方法可以基于这些x和y坐标将焦点设置到元素。

例如

//Get button coordinates
let coords = $("#gridButton3").getCoord(); 

//Get height of current element in focus
let itemHeight = $("#gridButton").scrollHeight;

//Delta value representing some space in between elements
const delta = 30; 

//coords.x = 200
//coords.y = 50
//itemHeight  = 200

鉴于以上这些值是在n x n网格中,假设我想将焦点设置在gridButton3下方的网格按钮上。

我将执行以下操作:

let {focusX , focusY } = coords;

//Only changing y coordinate because we are navigating down, x coordinates doesn't change
focusY = focusY + itemHeight + delta;


//Here is the part I need some insight on

//scroll to new y location 
$('html, body').animate({
    scrollTop: focusY 
}, 500)

//Now focus on element at coordinates (focusX,focusY)

我知道如何通过元素id或某些选择器设置焦点,我需要弄清楚如何基于给定x,y的元素来实现焦点。

1 个答案:

答案 0 :(得分:0)

要从DOM中的某个点获取元素,可以使用document.elementFromPoint()