gpt4 book ai didi

javascript - 动态设置选择元素宽度等于其选项内容宽度

转载 作者:搜寻专家 更新时间:2023-10-30 21:44:34 27 4
gpt4 key购买 nike

我试图使选择元素的宽度等于它的 Angular 选项文本宽度。

我的 HTML 组件看起来像这样:

<form [formGroup]="profileForm">
...
<select (change)="adjustSelectWidth($event.target)" formControlName="members">
<option value="1">Me</option>
<option value="2">Me, my spouse</option>
<option value="3">Me, my spouse and my kids</option>
</select>
...
</form>

我尝试过的:

  • 使用 clientWidth 获取选项元素宽度,然后将其应用于选择元素,但该宽度为 0。
export class AppComponent  {
profileForm = new FormGroup({
members : new FormControl(''),
})

adjustSelectWidth(e){
const optionValue = this.profileForm.get('members').value;
const optionWidth = document.querySelector(`option[value="${optionValue}"]`).clientWidth;
e.style.width= optionWidth + "px"
}
}
  • 获取选项的 innerHTML 长度,然后将其与固定像素相乘,但它不是动态选项
export class AppComponent  {
profileForm = new FormGroup({
members : new FormControl(''),
})

adjustSelectWidth(e){
const optionValue = this.profileForm.get('members').value;
const optionTextLength = document.querySelector(`option[value="${optionValue}"]`).innerHTML.length;
e.style.width= optionTextLength*8 + "px";
}
}
  • 将选项的 innerHTML 附加到用于测量宽度的 span 元素,但是当我将它应用到 select 元素时,那个 span clientWidth 不准确
export class AppComponent  {
//This temp is bind to a span via string interpolation {{...}}
temp:string;

profileForm = new FormGroup({
members : new FormControl(''),
})

adjustSelectWidth(e){
const optionValue = this.profileForm.get('members').value;
const optionText = document.querySelector(`option[value="${optionValue}"]`).innerHTML;
this.temp = optionText;
const spanWidth = document.querySelector(`.temp`).clientWidth;
e.style.width = spanWidth + "px";
}
}

由于我使用的是 Angular,所以我不喜欢使用 JQuery。此外,为什么 clientWidth 似乎无法解决我的问题

我创建了一个 stackbliz 示例:https://stackblitz.com/edit/angular-bbimkz

最佳答案

有一种方法可以测量文本宽度。我认为它足够可靠,但在性能方面可能有点贵,当然这取决于您的应用程序。 (Stackblitz 中的简单示例没有性能问题。)

方法是在包含要测量的文本的文档中实际附加一个隐藏元素,读取clientWidth,并立即移除该元素。

修改adjustSelectWidth()如下:

adjustSelectWidth(e: HTMLSelectElement){
// assuming something is always selected, please test!
const displayedText = e.options[e.selectedIndex].innerText;
const dummy = document.createElement('div');
dummy.innerText = displayedText;
dummy.style.position = 'absolute';
dummy.style.visibility = 'hidden';
document.body.insertBefore(dummy, document.body.firstChild);
const measuredWidth = dummy.clientWidth;
document.body.removeChild(dummy);
e.style.width = (measuredWidth + 30) + 'px'
}

修改后的 Stackblitz:https://stackblitz.com/edit/angular-mpjxbd?file=src/app/app.component.ts - 在最新的 Firefox、Chrome、Edge 中测试

关于javascript - 动态设置选择元素宽度等于其选项内容宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57786475/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com