我需要在下拉列表中选择文本(select / option)。我设法让它在Firefox 10中运行,但在Chromiun 16中没有。
Firefox和Chrome:
Chromiun的问题在于元素的返回宽度始终为零:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<select id="the_select" onchange="setWidth();">
<option value="1">Red 12,098</option>
<option value="2">Green 234</option>
<option value="3">Blue 2,120</option>
</select>
<select id="stub" style="">
<option id="o"></option>
</select>
</body>
</html>
<script type="text/javascript">
function setWidth() {
$('#stub').css('display', 'block');
var width, selectedWidth, maxWidth = 0;
var optionText
var extraPixels = 15;
var $o = $('#the_select option');
$o.each(function(){
optionText = $(this).text();
width = $('#o').html(optionText).width();
if (width > maxWidth) maxWidth = width + extraPixels;
if ($(this).prop('selected')) {
selectedWidth = width;
}
});
$('#the_select').css('word-spacing', maxWidth - selectedWidth + 'px');
$o.each(function(){
optionText = $(this).text();
width = $('#o').html(optionText).width();
extraPixels = maxWidth - width;
$(this).css('word-spacing', extraPixels + 'px');
});
$('#stub').css('display', 'none');
}
$(document).ready(setWidth);
</script>
如何让它在Chrome中运行?
答案 0 :(得分:1)
此版本适用于Firefox 10和Chromium 16.它在IE 9中不起作用,因为css属性word-spacing
在<select>
内无效。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<select id="the_select" onchange="justify();">
<option value="1">Red 234</option>
<option value="2">Green 12,098</option>
<option value="3">Blue 2,120</option>
</select>
<select id="stub" style="display:none;"><option></option></select>
</body>
</html>
<script type="text/javascript">
function justify() {
$('#stub').css('display', 'block');
var selectedWidth, maxWidth = 0;
var width = [];
var extraPixels = 15;
$('#the_select option').each(function(){
$('#stub option').html($(this).html());
width.push($('#stub').outerWidth());
if (width[width.length - 1] > maxWidth)
maxWidth = width[width.length - 1] + extraPixels;
if ($(this).prop('selected'))
selectedWidth = width[width.length - 1];
});
$('#stub').css('display', 'none');
$('#the_select')
.css('word-spacing', maxWidth - selectedWidth + 'px')
.css('width', maxWidth + 'px');
$('#the_select option').each(function(){
extraPixels = maxWidth - width.shift();
$(this).css('word-spacing', extraPixels + 'px');
});
}
$(document).ready(justify);
</script>