在这个 jsfiddle 示例中 http://jsfiddle.net/jitendravyas/Apz9e/8/
有一个下拉菜单。问题是下拉菜单的标签会根据所选选项的长度改变大小。
通过 jquery,我想设置宽度始终匹配列表中最长的元素。
请在此处进行编辑 http://jsfiddle.net/jitendravyas/Apz9e/8/
HTML
<form method="post" action="">
<div>
<select class="select" title="Select one">
<option selected>Select</option>
<option>Blue</option>
<option >Red</option>
<option>Green</option>
<option>Yellow</option>
<option>Brown</option>
</select>
</div>
</form>
JavaScript
$(document).ready(function(){
if (!$.browser.opera) {
// select element styling
$('select.select').each(function(){
var title = $(this).attr('title');
if( $('option:selected', this).val() != '' ) title = $('option:selected',this).text();
$(this)
.css({'z-index':10,'opacity':0,'-khtml-appearance':'none'})
.after('<span class="select">' + title + '</span>')
.change(function(){
val = $('option:selected',this).text();
$(this).next().text(val);
})
});
};
});
CSS
body {
margin:0;
padding:40px 40px;
background:#fff;
color:#555;
line-height:180%;
}
/* all form DIVs have position property set to relative so we can easily position newly created SPAN */
form div {position:relative;
}
/* setting the width and height of the SELECT element to match the replacing graphics */
span.select, select.select {
width:auto ;
height:auto ;
font:3.2em Arial, Helvetica, sans-serif;
font-weight:bold;
padding:1% 1%
}
select.select{
position:relative;
z-index:10;
line-height:1;
padding:0 0.5%
}
select option {padding-top:3px; border-bottom:1px solid red}
/* dynamically created SPAN, placed below the SELECT */
span.select{
position:absolute;
bottom:0;
float:left;
left:2px;
line-height:1;
text-indent:10px
background: #ffffff;
background: url('images/color-arrow.png') no-repeat, -moz-linear-gradient(top, #ffffff 0%, #a9a9a9 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#a9a9a9));
background: -webkit-linear-gradient(top, #ffffff 0%,#a9a9a9 100%);
background: linear-gradient(top, #ffffff 0%,#a9a9a9 100%);
cursor:default;
z-index:1;
border:#dadada 1px solid;
border-radius:6px;
background-position: 100% center;
text-shadow:0px 1px 1px #fff;
}
最佳答案
一种解决方案是制作选择框并将其设置为其中一个选项的宽度
var sel=//get select element
sel.style.width=$('select>option').clientWidth+'px';
我不确定确切的 jquery 语法,但这应该能让您有所了解。此外,这并未考虑边距,因此您可能需要对此进行调整。
关于javascript - 如何使用jquery获取下拉列表中最长单词的跨度大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8426694/