javascript - jquery:你能详细说明这个职位是如何工作的吗?新手使用偏移等进行定位

标签 javascript jquery positioning

跟踪这个jquery自动完成函数,有人可以详细解释这里发生了什么吗?

function showResults() {
    // get the position of the input field right now (in case the DOM is shifted)
    var pos = findPos(input);
    // either use the specified width, or autocalculate based on form element
    var iWidth = (options.width > 0) ? options.width : $input.width();
    // reposition
    $results.css({
        width: parseInt(iWidth) + "px",
        top: (pos.y + input.offsetHeight) + "px",
        left: pos.x + "px"
    }).show();
};

它使用这个函数:

function findPos(obj) {
    var curleft = obj.offsetLeft || 0;
    var curtop = obj.offsetTop || 0;
    while (obj = obj.offsetParent) {
        curleft += obj.offsetLeft
        curtop += obj.offsetTop
    }
    return {x:curleft,y:curtop};
}

引用:http://www.pengoworks.com/workshop/jquery/lib/jquery.autocomplete.js

最佳答案

offsetLeftoffsetTop 是描述 obj 与其包含元素偏移多少像素的属性。这个函数的作用是:

  1. 计算 obj 与其父元素的偏移量,并将这些值保存在变量中
  2. obj 设置为上次计算的项目的父元素
  3. 转到 1。重复此操作,直到到达 DOM 的顶层。

这会计算 obj 距渲染页面顶部和左侧的像素数。

关于javascript - jquery:你能详细说明这个职位是如何工作的吗?新手使用偏移等进行定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/965782/

相关文章:

javascript - 服务器端浏览器

jquery - jQuery 语法错误?

html - 如何使用 css 网格选择整个网格元素,同时保持元素居中对齐并在悬停时保持静止

javascript - 使用相同的值更新对象

javascript - 如何使用字符串数组调用 JavaScript 函数

javascript - 从单个 anchor 标记传递大量数据

css - 获取内容 div 到页面底部

html - 带边框的定位标志

javascript - 格式化 Ember 图表的数据。

javascript - 访问变量内的 DOM 元素