简体   繁体   English

如何使用jQuery在给定位置获得最高元素?

[英]How do I get the top most element at a given location with jQuery?

I have a draggable which on the stop event, I want move to a certain boundary IF it wasnt dragged onto anything else. 我有一个可拖动对象,在停止事件上,如果它没有拖动到其他任何对象上,我想移到某个边界。 Problem: the drop event handled by droppable occurs AFTER the stop event from the draggable handler. 问题:在可拖动处理程序的stop事件之后,发生了droppable处理的drop事件。 The stop handler for draggables gives the location that the draggable was dragged to, but I dont know how to determine what element is at that location. 可拖动对象的停止处理程序提供了可拖动对象被拖动到的位置,但是我不知道如何确定该位置上的元素。 Any ideas? 有任何想法吗?

You could probably just loop through the droppable elements and check their offset position. 您可能只需要遍历可放置元素并检查其偏移位置即可。 Combined with the width/height of each element, you can calculate which element the draggable was over when the stop event is fired. 结合每个元素的宽度/高度,您可以计算触发stop事件时可拖动对象在哪个元素上。 Something like this (this is untested, off the top of my head.) 这样的事情(未经测试,在我的头顶上)。

function stopCallback (x, y) {
    var $droppables = $(".droppable"),
        containedDraggableAtStop = function($item, left, top) {
            var itemL = $item.offset().left,
                itemT = $item.offset().top,
                itemR = itemL + $item.width,
                itemB = itemT + $item.height;

            if (top > itemT && top < itemB && left > itemL && left < itemR) {
                return true;
            }
            return false;
        },
        numDroppables = $droppables.length,
        i;

    // x, y are the coords passed from the stop function
    for (i = 0; i < numDroppables; i++) {
        if (containedDraggableAtStop($droppables.eq(i), x, y)) {
            return $droppables.eq(i);
        }
    }
    return -1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何使用JQuery从底部到顶部(最嵌套的元素首先)对表单进行迭代,而无需事先知道最深元素的ID? - How do I use JQuery to iterate a form from the bottom to the top, most nested element first without knowing the id of the deepest element beforehand? 在JQuery中,如何在用户单击鼠标从DOM中删除元素后,如何获取元素的offset()。top - In JQuery how do I get the offset().top of an element after a user removes an element from the DOM with a click 当我单击其任何一个子元素时,如何获取最顶层的父 ID? - How to get top most parent Id when I click on any one of its child element? 如何从javascript中的元素获取CSS属性顶部 - How do I get the CSS property top from a element in javascript Backbone.js - 给定一个元素,我如何获得视图? - Backbone.js - Given an element, how do I get the view? 获取jQuery中的顶级元素 - Get the top element in jQuery 如何获取jQuery中列表项的最上层父级的文本? - How to get the text of the top most parent of list item in jquery? 给定一个jQuery,如何获取第一个结果元素? - Given a jQuery, how to get the first result element? 如何更改画布元素的位置? - How do I change the location of a canvas element? 如何使用 cheerio (jquery) 获取给定元素的下一个 HTML 元素 - How to get the next HTML element of a given element using cheerio (jquery)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM