Почему значение стиля ширины не отображается на входе? - PullRequest
0 голосов
/ 28 мая 2019

Я пытаюсь взять ширину из div "demo" и поместить ее в значение "input number".Я не могу понять, где я допустил ошибку ...

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 ]

1 голос
/ 28 мая 2019

Эта проблема связана с тем, что значение 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>
1 голос
/ 28 мая 2019

Вам необходимо преобразовать 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>
...