Jquery 现在,我已经实现了以下行为:
加载文档时:选择的宽度已基于所选选项的宽度(不会重新绘制)Jquery 现在,我已经实现了以下行为:,jquery,select,resize,autoresize,dom-manipulation,Jquery,Select,Resize,Autoresize,Dom Manipulation,加载文档时:选择的宽度已基于所选选项的宽度(不会重新绘制) 更改时:选择的宽度将更新为新选择的选项的宽度 /*宽度、调整、基于内容*/ $(文档).on('change','width-content-based',function()){ 让文字_修改_字体; 让文本_修改_字符串; 让子体\u清空\u元素; 文本\u已修改\u字体= $(this.css('font-weight')+''+$(this.css('font-size')+''+$(this.css('font-family
/*宽度、调整、基于内容*/
$(文档).on('change','width-content-based',function()){
让文字_修改_字体;
让文本_修改_字符串;
让子体\u清空\u元素;
文本\u已修改\u字体=
$(this.css('font-weight')+''+$(this.css('font-size')+''+$(this.css('font-family'));
如果
(
$(此).is('select')
)
{
文本\修改的\字符串=
$(this.find(':selected').text();
子体\u清空\u元素=
$(this.find(“[data text]”);
}
其他的
{
文本\修改的\字符串=
$(this.val();
}
$(this.css({'width':text\u width\u estimate(text\u modified\u string,text\u modified\u font)+'px});
如果
(
子体\u清空的\u元素。长度
)
{
子体\u清空\u元素。每个(函数(){
$(this.text($(this.attr('data text')).removeAttr('data text');
});
}
});
/*文件,准备好了吗*/
$(文档).ready(函数(){
$('.width-content-based')。触发器('change');
});
/*TEXT WIDTH ESTIMATE*/函数TEXT_WIDTH_ESTIMATE(TEXT,font){let canvas=TEXT_WIDTH_ESTIMATE.canvas |(TEXT_WIDTH_ESTIMATE.canvas=document.createElement('canvas');let context=canvas.getContext('2d');context.font=font;let metrics=context.measureText(TEXT);return metrics.WIDTH+3;}
选择{-webkit外观:无;}
阿尔巴尼亚
这里有一个更现代的香草JS方法来解决这个问题。这与没有jQuery时的原理差不多
selectedIndex
的文本传递给该选项position:fixed
和visibility:hidden
样式添加到新的选择元素中。这样可以确保它不会影响布局,但仍可以测量其边界框getBoundingClientRect().width
const select=document.querySelector('select'))
select.addEventListener('change',(事件)=>{
让tempSelect=document.createElement('select'),
tempOption=document.createElement('option');
tempOption.textContent=event.target.options[event.target.selectedIndex].text;
tempSelect.style.cssText+=`
可见性:隐藏;
位置:固定;
`;
tempSelect.appendChild(tempOption);
event.target.after(tempSelect);
const tempSelectWidth=tempSelect.getBoundingClientRect().width;
event.target.style.width=`${tempSelectWidth}px`;
tempSelect.remove();
});
选择.dispatchEvent(新事件('change'))代码>
空头期权
一些更长的选择
一个包含大量文本的很长的选项
没有可靠的方法获取选项的宽度。您可以取而代之的是获取文本的长度
属性,并据此猜测所需的宽度。@Rorymcrossan我也想到了这一点,但在不同的浏览器屏幕分辨率设置下不会得到不同的结果?我还发现了这个可能的解决方案:这里的简单解决方案:这里有一个更现代的vanilla JS方法来解决这个问题:你的fiddle链接与OPs相同。好的方法,但你必须确保
文本的字体/大小与
相同。如果删除#width\u tmp{display:none;}
,您会发现
更大。这将导致
大于其应有值。文本越长,
中的空白就越大。下面是一个纯javascript的尝试版本:您也可以通过尝试在两个选择之间匹配字体来获得一些吸引力,有点类似:检查我的解决方案,它更简单、更简洁:)这里有一个更现代的香草JS方法来解决这个问题:我建议更改行var$test=$(“”)html(text)
tovar$test=$(“”).html(文本)
以确保创建的临时范围的字体大小与select元素的字体大小匹配。如果跨距的字体大小更小或更大,动态调整大小将被大小的差异抵消。大多数情况下有效!我使用引导的默认CSS总是将select元素的宽度设置为100%,这会返回不正确的宽度。我把追加从正文
改为#我的表单
和$(“”)改为$(“”)
,只是为了让我安心。不幸的是,它在Ipad/Android平板电脑上不起作用,你知道为什么吗?我认为在这些设备中,选项的字体大小可能不同,但如果我设置静态字体大小,则无法解决问题。我通过为表单元素提供静态字体大小来修复上述问题,我上面建议的是在脚本ISELF上提供一个静态字体大小这里有一个更现代的vanilla JS方法来解决这个问题:这已经被否决了,但它似乎在Firefox(而不是Chrome)中可以工作。很难阅读带有格式的代码示例-最好稍微整理一下:)
$(document).ready(function() {
$('select').change(function(){
$(this).width($('select option:selected').width());
});
});
select option{width:0; }
select option:hover{width:auto;}
<html><head><title>Auto size select</title>
<script>
var resized = false;
function resizeSelect(selected) {
if (resized) return;
var sel = document.getElementById('select');
for (var i=0; i<sel.options.length; i++) {
sel.options[i].title=sel.options[i].innerHTML;
if (i!=sel.options.selectedIndex) sel.options[i].innerHTML='';
}
resized = true;
sel.blur();
}
function restoreSelect() {
if (!resized) return;
var sel = document.getElementById('select');
for (var i=0; i<sel.options.length; i++) {
sel.options[i].innerHTML=sel.options[i].title;
}
resized = false;
}
</script>
</head>
<body onload="resizeSelect(this.selectedItem)">
<select id="select"
onchange="resizeSelect(this.selectedItem)"
onblur="resizeSelect(this.selectedItem)"
onfocus="restoreSelect()">
<option>text text</option>
<option>text text text text text</option>
<option>text text text </option>
<option>text text text text </option>
<option>text</option>
<option>text text text text text text text text text</option>
<option>text text</option>
</select>
</body></html>
// Function that helps to get the select element width.
$.fn.getSelectWidth = function() {
var width = Math.round($(this).wrap('<span></span>').width());
$(this).unwrap();
return width;
}
$(this).getSelectWidth();
$('#mySelect').change(function(){
var $selectList = $(this);
var $selectedOption = $selectList.children('[value="' + this.value + '"]')
.attr('selected', true);
var selectedIndex = $selectedOption.index();
var $nonSelectedOptions = $selectList.children().not($selectedOption)
.remove()
.attr('selected', false);
// Reset and calculate new fixed width having only selected option as a child
$selectList.width('auto').width($selectList.width());
// Add options back and put selected option in the right place on the list
$selectedOption.remove();
$selectList.append($nonSelectedOptions);
if (selectedIndex >= $nonSelectedOptions.length) {
$selectList.append($selectedOption);
} else {
$selectList.children().eq(selectedIndex).before($selectedOption);
}
});