Inner div inside an outer rotated div does not follow mouse in case dragging with jQuery UI

后端 未结 6 711
温柔的废话
温柔的废话 2021-02-07 05:04

I have an inner div inside an outer div. The inner div is draggable and outer is rotated through 40 degree. This is a test case. In an actual case it could be any angle. There i

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-07 06:04

    For Webkit only, the webkitConvertPointFromPageToNode function handles the missing behavior:

       var point = webkitConvertPointFromPageToNode(
           document.getElementById("outer"),
           new WebKitPoint(event.pageX, event.pageY)
       );
    

    jsFiddle: http://jsfiddle.net/kB4ra/108/

    To cover other browsers as well, you can use the method described in this StackOverflow answer: https://stackoverflow.com/a/6994825/638544

    function coords(event, element) {
      function a(width) {
        var l = 0, r = 200;
        while (r - l > 0.0001) {
          var mid = (r + l) / 2;
          var a = document.createElement('div');
          a.style.cssText = 'position: absolute;left:0;top:0;background: red;z-index: 1000;';
          a.style[width ? 'width' : 'height'] = mid.toFixed(3) + '%';
          a.style[width ? 'height' : 'width'] = '100%';
          element.appendChild(a);
          var x = document.elementFromPoint(event.clientX, event.clientY);
          element.removeChild(a);
          if (x === a) {
            r = mid;
          } else {
            if (r === 200) {
              return null;
            }
            l = mid;
          }
        }
        return mid;
      }
        var l = a(true),
            r = a(false);
        return (l && r) ? {
            x: l,
            y: r
        } : null;
    }
    

    This has the disadvantage of not working when the mouse is outside of the target element, but it should be possible to extend the area it covers by an arbitrary amount (though it would be rather hard to guarantee that it covers the entire window no matter how large).

    jsFiddle: http://jsfiddle.net/kB4ra/122/

    This can be extended to apply to #point by adding a mousemove event:

    $('#outer').mousemove(function(event){
       var point = convertCoordinates(event, $("#outer"));
    
        $("#point").css({left: point.x+1, top: point.y+1});          
    });
    

    Note that I adjust the x and y coordinates of #point by 1px to prevent it from being directly underneath the mouse; if I didn't do that, then it would block dragging #inner. An alternative fix would be to add handlers to #point that detect mouse events and pass them on to whichever element is directly underneath #point (and stopPropagation, so that they don't run twice on larger page elements).

    jsFiddle: http://jsfiddle.net/kB4ra/123/

提交回复
热议问题