2014-09-26 51 views
1

我想要做一個組合類似的東西,我需要在輸入上方對齊div。javascript:將絕對div對齊到另一個div上

我該如何計算正確的bottom css property的列表才能在輸入上方顯示?

示例代碼:

HTML

<div style="position:absolute;top:150px; left:150px;"> 
    <input/><span class="btn">V</span> 
</div> 
<div class="list" style="display:none;"> 
    <ul> 
     <li>Item 1</li> 
     <li>Item 2</li> 
     <li>Item 3</li> 
     <li>Item 4</li> 
    </ul> 
</div> 

CSS

.btn { 
    width: 10px; 
    height:10px; 
    background-color: black; 
    cursor: pointer; 
} 

.list { 
    position: absolute; 
    border: solid 1px black; 
} 

JS

$('.btn').click(function(){ 
    var list = $('.list'); 
    list.show(); 

    var inputOffset = $('input').offset(); 

    list.css({ 
     bottom: inputOffset.top, 
     left: inputOffset.left 
    }); 
}); 

FIDDLE

注: 的投入將工作就像一個過濾器,這樣列表的高度將發生變化。 我想讓瀏覽器保持列表對齊。這就是爲什麼我想在列表中設置正確的bottom值。

+0

如何糾正任何錯誤?請閱讀您自己的問題並更正。 – spender 2014-09-26 13:55:25

+0

所以你試圖讓列表直接出現在輸入和按鈕之上? – sma 2014-09-26 13:57:25

回答

0

使用top代替bottom和減去listinput位置的高度:

list.css({ 
    top: inputOffset.top - list.outerHeight(), 
    left: inputOffset.left 
}); 

http://jsfiddle.net/kdez58q9/2/

enter image description here

+0

這很好,但輸入將像過濾器一樣工作,因此列表的高度將會改變。我想讓瀏覽器保持列表對齊。這就是爲什麼我想在列表中設置適當的底部值。 – Levi 2014-09-26 14:19:24

0

你可以用CSS做

http://jsfiddle.net/Rykus0/kdez58q9/3/

(只注意到你想在上面輸入...以下是有一些調整,更新的小提琴做到這一點:http://jsfiddle.net/Rykus0/kdez58q9/5/

HTML

<div class="dropdown"> 
    <input/><span class="btn">V</span> 
    <div class="list" style="display:none;"> 
     <ul> 
      <li>Item 1</li> 
      <li>Item 2</li> 
      <li>Item 3</li> 
      <li>Item 4</li> 
     </ul> 
    </div> 
</div> 

CSS

.btn { 
    width: 10px; 
    height:10px; 
    background-color: black; 
    cursor: pointer; 
} 

.list { 
    position: absolute; 
    border: solid 1px black; 

    /* To make the list on top, change to bottom: 100%;*/ 
    top: 100%; 

    left: 0; 
} 

.dropdown { 
    position: relative; 

    /* If you want the list on top, be sure to add some space above the input */ 
} 

JS

$('.btn').on('click', function(){ 
    $('.list').toggle(); 
}); 
+1

看起來不錯,但我的組件並不那麼簡單。該列表將作爲身體的孩子呈現,但輸入和按鈕可以在dom中的任何級別上。 – Levi 2014-09-26 14:23:43

+0

我明白了,所以這兩個可能無法在DOM中擁有相同的祖先。我不確定你的瀏覽器需求是什麼,但你可以查看HTML5'datalist'元素並輸入'list'屬性。這是來自Wufoo http://www.wufoo.com/html5/attributes/05-list.html的演示。這裏是一個polyfills列表:https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills#datalist – 2014-09-26 18:49:35