为什么在输入中不显示宽度样式值?

时间:2019-05-28 08:27:03

标签: javascript input onclick styles return-value

我正在尝试从“演示” div中获取宽度,并将其放入“输入数字”值中。我不知道我在哪里犯错了...

function myFunction() {
    var element = document.getElementById("poster"),
    style = window.getComputedStyle(element),
    width = style.getPropertyValue('width');
  
  document.getElementById("demo").value = width;
}
 
<div id="poster" style="width:35px;height:45px;background-color:blue;"></div>

<input id="demo" type="number" placeholder="0" min="" max="" step="0.1">

<button onclick="myFunction()" type="button">Click Me!</button>
 

2 个答案:

答案 0 :(得分:1)

您需要将width转换为number,因为您使用input number而不是文本。实际上,您的width是一个字符串(35像素)。

function myFunction() {
    var element = document.getElementById("poster"),
    style = window.getComputedStyle(element),
    width = style.getPropertyValue('width');

  document.getElementById("demo").value = parseFloat(width);
}
<div id="poster" style="width:35px;height:45px;background-color:blue;"></div>

<input id="demo" type="number" placeholder="0" min="" max="" step="0.1">

<button onclick="myFunction()" type="button">Click Me!</button>

答案 1 :(得分:1)

此问题是因为width的值为35px,因此,在px类型为document.getElementById("demo").value时,应将input分配给number以编号<div id="poster" style="width:35px;height:45px;background-color:blue;"></div> <input id="demo" type="number" placeholder="0" min="" max="" step="0.1"> <button onclick="myFunction()" type="button">Click Me!</button> <script> function myFunction() { var element = document.getElementById("poster"), style = window.getComputedStyle(element), width = style.getPropertyValue('width').match(/\d+/); document.getElementById("demo").value = width; } </script> 如下代码

35px

如果您想获取没有单位的宽度编号,例如35%35将获得 <div id="poster" style="width:35px;height:45px;background-color:blue;"></div> <input id="demo" type="number" placeholder="0" min="" max="" step="0.1"> <select id="unit" > <option >none</option> <option value="%">%</option> <option value="px">px</option> </select> <button onclick="myFunction()" type="button">Click Me!</button> <script> function myFunction() { var element = document.getElementById("poster"), width = element.style["width"].match(/\d+/), unit = element.style["width"].match(/[^\d]+/); document.getElementById("unit").value = unit document.getElementById("demo").value = width; } </script> ,您可以使用以下代码:

    <mat-form-field [formGroup]="formGroup" class="mat-form-field--no-underline">
        <!-- Important part, input with matInput -->
        <input matInput style="display: none!important">
        <mat-selection-list #preConditions [formControl]="preexistingControl" [(ngModel)]="controlAnswer.value">
            <mat-list-option *ngFor="let preExistingCond of preExistingCondList">
                {{preExistingCond.value}}
            </mat-list-option>
        </mat-selection-list>
     </mat-form-field>