Jquery 获取项目的Html.listbox的计数和高度
使用Jquery 获取项目的Html.listbox的计数和高度,jquery,asp.net-mvc,Jquery,Asp.net Mvc,使用 C# MVC5 剃刀3 我有一个Html.ListBoxFor @Html.ListBoxFor( x => x.sunSelectedList, Model.sunList, new { @class = "eligibleAvailableListBox" } ) 我有jQuery javascript @section Scripts { <scrip
- C#
- MVC5
- 剃刀3
@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>
}
@节脚本{
$(函数(){
var ssList=$(“#sunSelectedList”);
//上述变量有效,并包含所有项
});
}
使用变量ssList,如何获取选项的数量和每个项目的客户机高度?获取选项的数量
var options = $("#sunSelectedList").children('option');
var optionCount = options.length;
要获取每个选项的高度,请使用或
编辑
在文档中,“所有选项元素都被认为是隐藏的,无论它们处于何种选定状态。”因此.height()
或.outerHeight()
实际上总是返回0
。使用window.getComputedStyle(this,null).lineHeight代码>不可靠,因为Chrome可能返回正常值
而不是一个数字。一种可能的解决方法是将选项的内容复制到临时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();
});
选项。每个(功能(索引、项){
var temp=$('').text($(this.text());
$('body')。追加(临时);
控制台日志(温度高度());
//或
console.log(window.getComputedStyle(temp[0],null).height);
移除温度();
});
您应该发布呈现的HTMLLength作品。高度计算不适用;outerHeight始终返回0,就像outerHeight(true)一样。然而,经检查,$(this).context.currentStyle.lineHeight确实给出了1.4285-我想是在em中?我应该用这个吗?事实上。。。window.getComputedStyle(this,null).lineHeight报告“20.28px”-我可以使用它吗?结果是jquery将所有选项
元素报告为隐藏(即使它们在屏幕上可见),这就是.height()
返回0
的原因。使用lineHeight
如果不可靠,例如Chrome可能返回normal
而不是一个数字。我将编辑我的答案,以包括一个可能的解决方法,但我还没有对它进行足够的测试,以了解它的可靠性。我将您的编辑与Temp div&itemHeight=Temp.height()一起使用;optionTotalHeight+=项目高度+5;Safari、Opera和Chrome需要额外的5个像素来精确显示列表框的大小(不需要滚动条)。IE和FireFox只需为每个项目增加3个像素即可完美显示列表框。函数window.getComputedStyle with height或lineHeight返回一个更精确的“15.61px”,但是您还需要使用parseFloat,因为它是一个文本值。我希望我可以在VS 2013中使用Chrome作为默认浏览器进行调试,以查看这些返回值是什么……我试图编辑你的函数的高度,以关闭函数;(2个字符)-仅用于语法更正-但我不允许保存少于6个字符的编辑…哈哈
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();
});