2012-02-29 402 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

相關問題