This issue occurs because the #width_tmp
is nested under .input-group-btn
so it inherits the font-size: 0;
property from bootstrap. Therefore, the calculated width of the element is always zero:
To fix this, just move the <span id="width_tmp"></span>
so it's not inside the input group.
Pure JS Solution
// resize on initial load
document.querySelectorAll("select").forEach(resizeSelect)
// delegated listener on change
document.body.addEventListener("change", (e) => {
if (e.target.matches("select")) {
resizeSelect(e.target)
}
})
function resizeSelect(sel) {
let tempOption = document.createElement('option');
tempOption.textContent = sel.selectedOptions[0].textContent;
let tempSelect = document.createElement('select');
tempSelect.style.visibility = "hidden";
tempSelect.style.position = "fixed"
tempSelect.appendChild(tempOption);
sel.after(tempSelect);
sel.style.width = `${+tempSelect.clientWidth + 4}px`;
tempSelect.remove();
}
Demo in jsFiddle and Stack Snippets
// resize on initial load
document.querySelectorAll("select").forEach(resizeSelect)
// delegated listener on change
document.body.addEventListener("change", (e) => {
if (e.target.matches("select")) {
resizeSelect(e.target)
}
})
function resizeSelect(sel) {
let tempOption = document.createElement('option');
tempOption.textContent = sel.selectedOptions[0].textContent;
let tempSelect = document.createElement('select');
tempSelect.style.visibility = "hidden";
tempSelect.style.position = "fixed"
tempSelect.appendChild(tempOption);
sel.after(tempSelect);
sel.style.width = `${+tempSelect.clientWidth + 4}px`;
tempSelect.remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="2">Some longer option</option>
<option value="1">Short option</option>
<option value="3">An very long option with a lot of text</option>
</select>
<select>
<option>Short option 2</option>
<option>Some longer option 2</option>
<option selected>An very long option with a lot of text 2</option>
</select>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…