javascript/jquery または css で html の<select>/@Html.DropDownList
自動幅を作成して、現在選択されている項目に収まるようdiplay:inline-block
にする方法はありwidth:auto
ますか?
13589 次
4 に答える
10
私の答えは D3mon-1stVFW のものと似ていますが、代わりに非表示のドロップダウンを使用して幅を動的に設定します。非表示のスタイルと「実際の」スタイルに同じスタイルを使用している限り、異なるフォント サイズ、装飾などを考慮する必要があります。HTML は次のとおりです。
<!-- this is our hidden "template" drop-down that we'll
use to determine the size of our "real" one -->
<select id="template" style="display:none;">
<option id="templateOption"></option>
</select>
<!-- this is our "real" template that will be re-sized -->
<select id="sel">
<option>Short</option>
<option>Really, Really, Really Long</option>
</select>
そしてJavascript:
function setSelectWidth() {
var sel = $('#sel');
$('#templateOption').text( sel.val() );
// for some reason, a small fudge factor is needed
// so that the text doesn't become clipped
sel.width( $('#template').width() * 1.03 );
}
$(document).ready( function() {
setSelectWidth();
$('#sel').change( function() {
setSelectWidth();
} );
});
JSFiddle はこちら: http://jsfiddle.net/kn9DF/1/
于 2012-04-24T23:09:33.633 に答える
1
私が書いたこのサンプルを使用してください。リストを作成するときも同じように使用し、デフォルトを選択してスパンに設定し、その幅を取得します。
<script>
function newSelected(ele){
document.getElementById('jsize').innerHTML = ele.value;
document.getElementById('selectList').style.width = ($(jsize).width()+30)+'px';
}
</script>
<span id="jsize" style="display:none"></span><br />
<select id="selectList" onchange="newSelected(this);">
<option>small item</option>
<option>a really big long item</option>
</select>
http://jsfiddle.net/39ffp/2/を参照 してください。微調整できます
于 2012-04-24T22:18:06.420 に答える