簡體   English   中英

動態設置選擇元素寬度等於其選項的內容寬度

[英]Set select element width equal to it's option's content width dynamically

我試圖使選擇元素寬度等於它的角度選項文本寬度。

我的 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 中測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM