感谢您的阅读。我是一个有点新的jQuery和我试图让一个脚本,我可以包括我所有的网站,以解决一直让我发疯的一个问题...JQuery选择框和循环帮助
问题: 长选项中选择框被切在Internet Explorer中关闭。例如,这些选择框: http://discoverfire.com/test/select.php
在Firefox中,它们很好,但在IE中,选项在下拉时会被截断到选定宽度。
解决办法: 我所希望做的,是创建一个脚本,我可以包括在任何网页,将执行以下操作:通过网页上的所有选择
循环。
对于每个选择: 答:循环选项。 B.找到最长选项的宽度。 C.将一个函数绑定到焦点上的宽度(或者点击...)。 D.绑定一个函数以缩小模糊时的原始宽度。
我设法为一个选择框做了大部分第2步。
我发现,得到的选项宽度是一个问题(特别是在IE),所以环通过和复制的每个选项的跨度,测得的跨宽的文本,和所使用的时间最长的一个作为宽度选择将扩大到。也许有人有一个更好的主意。
下面是代码
<script type='text/javascript'>
$(function() {
/*
This function will:
1. Create a data store for the select called ResizeToWidth.
2. Populate it with the width of the longest option, as approximated by span width.
The data store can then be used
*/
// Make a temporary span to hold the text of the options.
$('body').append("<span id='CurrentOptWidth'></span>");
$("#TheSelect option").each(function(i){
// If this is the first time through, zero out ResizeToWidth (or it will end up NaN).
if (isNaN($(this).parent().data('ResizeToWidth'))) {
$(this).parent().data('OriginalWidth', $(this).parent().width());
$(this).parent().data('ResizeToWidth', 0);
$('CurrentOptWidth').css('font-family', $(this).css('font-family'));
$('CurrentOptWidth').css('font-size', $(this).css('font-size'));
$('CurrentOptWidth').css('font-weight', $(this).css('font-weight'));
}
// Put the text of the current option into the span.
$('#CurrentOptWidth').text($(this).text());
// Set ResizeToWidth to the longer of a) the current opt width, or b) itself.
//So it will hold the width of the longest option when we are done
ResizeToWidth = Math.max($('#CurrentOptWidth').width() , $(this).parent().data('ResizeToWidth'));
// Update parent ResizeToWidth data.
$(this).parent().data('ResizeToWidth', ResizeToWidth)
});
// Remove the temporary span.
$('#CurrentOptWidth').remove();
$('#TheSelect').focus(function(){
$(this).width($(this).data('ResizeToWidth'));
});
$('#TheSelect').blur(function(){
$(this).width($(this).data('OriginalWidth'));
});
alert($('#TheSelect').data('OriginalWidth'));
alert($('#TheSelect').data('ResizeToWidth'));
});
</script>
和选择:
<select id='TheSelect' style='width:50px;'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
<option value='42,693,748,756'>Forty-two billion, six-hundred and ninety-three million, seven-hundred-forty-some-odd..... </option>
<option value='5'>Five</option>
<option value='6'>Six</option>
<option value='7'>Seven...</option>
</select>
希望,如果你想运行它,这会为你跑,或者你可以看到它在这里的行动:http://discoverfire.com/test/select.php。
我需要帮助: 这需要一点光泽,但如果指定选择框,似乎工作正常。
但是,我似乎无法弄清楚如何使用循环将其应用于页面上的所有选择框。到目前为止,我有这个:
$('select').each(
function(i, select){
// Get the options for the select here... can I use select.each...?
}
);
此外,有没有更好的方法来获得每个选择最长的选项的长度?跨度很接近,但不是很精确。问题是IE对实际选择的选项宽度返回零。
任何想法都非常值得欢迎,无论是对于提出的问题,还是对我的代码的任何其他改进。
谢谢!
这些答案都非常有帮助 - 谢谢! – Eli 2008-10-13 22:15:52