使用JS获取按钮的宽度?

问题描述 投票:0回答:1

我在index.html中有一个按钮,是在html文件而不是javascript文件中创建的。我正在尝试使用纯Javscript获取按钮的宽度。我不使用jQuery,也不会选择其他JS库。我尝试过的:

index.html

<button id="btn-resize-me" onClick="resizeButton();"></button>

javascript.js

function resizeButtom() {
    var btn = document.getElementById('btn-resize-me');
    alert(btn.style.width); // alerts blank
    alert(parseInt(btn.style.width); // alerts NaN, because the value is a blank
    btn.style.width = toString(parseInt(btn.style.width) - 20) + "px"; // does not work!
}
javascript button resize
1个回答
0
投票

您需要设置宽度,然后可以使用脚本检索它:

  function resizeButton() {
        var btn = document.getElementById('btn-resize-me');
    alert(parseInt(btn.style.width,10)); // 
        alert(parseInt(btn.style.width)); 
        btn.style.width = toString(parseInt(btn.style.width) - 20) + "px"; 
    }
<button id="btn-resize-me" onClick="resizeButton()" style="width:200px; height:20px;"></button>
© www.soinside.com 2019 - 2024. All rights reserved.