簡體   English   中英

獲取Html.ListBoxFor的計數和高度

[英]Get count and height of Html.ListBoxFor item

使用

  • C#
  • MVC 5
  • 剃刀3

我有一個Html.ListBoxFor ...

          @Html.ListBoxFor(
            x => x.sunSelectedList,
            Model.sunList,
            new { @class = "eligibleAvailableListBox" }
            )

我有jQuery javascript。

@section Scripts {
<script type="text/javascript">
    $(function () {

        var ssList = $("#sunSelectedList");

        // the variable above is valid and contains all items

    });
</script>
}

使用變量ssList,如何獲得每個項目的選項數和客戶高度?

獲取選項數量

var options = $("#sunSelectedList").children('option');
var optionCount = options.length;

要獲取每個選項的高度,請使用.height().outerHeight()

options.each(function(index, item) {
  var optionHeight = $(this).outerHeight();  // includes padding and borders
}

編輯

從文檔中, “所有選項元素都被視為隱藏的,無論其處於選擇狀態如何。” 因此.height().outerHeight()實際上總是返回0 使用window.getComputedStyle(this,null).lineHeight; 不可靠,因為Chrome可能會返回normal而不是數字。 可能的解決方法是將選項的內容復制到臨時div元素中並計算高度。

options.each(function(index, item) {
  var temp = $('<div></div>').text($(this).text());
  $('body').append(temp);
  console.log(temp.height());
  // or
  console.log(window.getComputedStyle(temp[0], null).height);
  temp.remove();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM