2012-02-29 403 views
7

好的,这是我的问题。 使用jQuery UI位置。可以将元素相对于屏幕上的另一个元素进行定位。它会在放置在屏幕上的元素上设置左侧和顶部CSS属性。jQuery UI设置“right”和“bottom”而不是“left”和“top”的位置

我想要做的不是设置左侧和顶部,而是想设置右侧和底部,以便定位元素增长或缩小时,它会沿正确的方向增长/收缩。

让我进入细节。 好吧,我想要的是,如果一个元素的位置是正确的,那么我想设置right css属性而不是left,如果一个元素位于其底部,那么我想设置bottom而不是top。我可以使用jQuery UI Position的using属性来做到这一点,但碰到碰撞检测问题。如果碰撞检测设置为flip并且元素翻转了,我想检测这个并确定是否需要设置right而不是leftbottom而不是top。查看下面的代码以更好地了解我正在尝试做什么。

$('#somediv').position({ 
    my: 'right bottom', 
    at: 'right top', 
    of: $('#someotherdiv'), 
    offset: '0 5', 
    collision: 'flip flip', 
    using: function(pos) { 

     // Figure out the right and bottom css properties 
     var right = $(window).width() - pos.left - $(this).outerWidth(true); 
     var bottom = $(window).height() - pos.top - $(this).outerHeight(true); 

     // Position the element so that right and bottom are set. 
     $(this).css({left: '', right: right, top: '', bottom: bottom}); 
    } 
}); 

这很好用,除非div从碰撞检测中翻转过来。如果水平翻转,我想设置left而不是right,如果垂直翻转,我想设置top而不是bottom

理想的解决方案是,如果有一种方法可以告诉(在using函数中)元素是否翻转以及朝哪个方向。所以,任何人有任何想法来弄清楚是否使用碰撞检测翻转了一个元素?

+0

任何人?我是否清楚问题? – 2012-03-02 07:53:34

回答

3

好吧,想通了....这是我的尝试来解释我是如何工作的。 您需要做的是在using函数中再次调用位置。在没有碰撞检测的情况下调用一次,在碰撞检测时调用一次如果位置发生变化,则翻转。以下是一些带注释的示例代码。

$('#somediv').position({ 
    my: 'right bottom', 
    at: 'right top', 
    of: $('#someotherdiv'), 
    offset: '0 5', 
    collision: 'flip flip', 
    using: function (pos1) { 

     // OK, we got a position once inside the pos1 variable, 
     // let's position it again this time without collision detection. 
     $(this).position({ 
      my: 'right bottom', 
      at: 'right top', 
      of: $('#someotherdiv'), 
      offset: '0 5', 
      collision: 'none none', 
      using: function(pos2) { 
       var hpos = 'right'; 
       var vpos = 'bottom'; 

       // Check to see if it was flipped horizontal 
       if (pos1.left != pos2.left) { 
        /* It was flipped horizontally so position is now 
         my: 'left bottom', 
         at: 'left top' 
        */ 
        hpos = 'left'; 
       } 

       // Check to see if it was flipped vertical 
       if (pos1.top != pos2.top) { 
        /* It was flipped vertically */ 
        vpos = 'top'; 
       } 

       // Figure out the right and bottom css properties 
       var right = $(window).width() - pos1.left - $(this).outerWidth(true); 
       var bottom = $(window).height() - pos1.top - $(this).outerHeight(true); 

       // Set the horizontal position 
       if (hpos == 'right') { 
        $(this).css({left: '', right: right}); 
       } else { 
        $(this).css({left: pos1.left, right: ''}); 
       } 

       // Set the vertical position 
       if (vpos == 'bottom') { 
        $(this).css({top: '', bottom: bottom}); 
       } else { 
        $(this).css({top: pos1.top, bottom: ''}); 
       } 
      } 
     }); 
    } 
}); 

如果有人有一个更有效的想法,请让我知道。谢谢。

+0

太棒了!感谢张贴这... – 2013-07-26 21:17:48

+0

任何其他方法? – DioNNiS 2015-05-23 01:49:43

相关问题