下拉列表宽度适合选定的项目文本 [英] Drop down list width fit selected item text

查看:92
本文介绍了下拉列表宽度适合选定的项目文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript / jquery或css中有一种方法可以使html < select> / @ Html.DropDownList 自动调整宽度,以适应当前选定的项目,我尝试过 diplay:inline-block width:auto 但宽度总是似乎适合列表中的最大项目?

解决方案

我的答案与D3mon-1stVFW类似,但是使用隐藏下拉列表来动态设置宽度。只要你对隐藏和真实的样式使用相同的样式,它应该考虑到不同的字体大小,装饰等等。这里是HTML:

 <! - 这是我们隐藏的模板下拉菜单,我们将使用
来确定真正的大小 - >
< select id =templatestyle =display:none;>
< option id =templateOption>< / option>
< / select>
<! - 这是我们的真实模板,将被重新设定大小 - >
< select id =sel>
< option>短< / option>
< option>真的,真的,真的很长< / option>

和Javascript:

 函数setSelectWidth(){
var sel = $('#sel');
$('#templateOption')。text(sel.val());
//出于某种原因,需要一个小巧的因子
//这样文本不会被裁剪
sel.width($('#template')。width() * 1.03);

$ b $(document).ready(function(){
setSelectWidth();
$ b $('#sel')。change( function(){
setSelectWidth();
});
});

JSFiddle here: http://jsfiddle.net/kn9DF/1/


Is there a way in javascript/jquery or css to make html <select>/@Html.DropDownList auto width so it fits currently selected item, I tried with diplay:inline-block and width:auto but width always seems to fit largest item on list?

解决方案

My answer is similar to D3mon-1stVFW's, but instead uses a hidden drop-down to set the width on dynamically. As long as you use the same styling for your hidden and "real" one, it should account for different font sizes, decoration, etc. Here's the 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>​

And the 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 here: http://jsfiddle.net/kn9DF/1/

这篇关于下拉列表宽度适合选定的项目文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆