首页 > 解决方案 > 为什么宽度样式值不显示在输入中?

问题描述

我正在尝试从“演示”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>
 

标签: javascriptinputonclickstylesreturn-value

解决方案


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

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>


推荐阅读