使用JS获取按钮的宽度?

时间:2019-12-23 17:44:48

标签: javascript button resize

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

console.log("1");
[2].forEach(value => console.log(value));
console.log("3");
.forEach

stylesheet.css

  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!
    }

我无法设置按钮宽度,因为它是浏览器中加载的字体宽度(特定浏览器可能不会加载默认字体)和左右两侧14px,7px填充的总和。 / p>

动机: 当我按下一个按钮时,我希望另一个按钮获得1px纯黑色的边框。这是完美的作品,但是由于边框的原因,按钮的宽度增加了2px,将其他菜单项按钮移动了2px,这看起来很奇怪。我虽然将更改后的按钮(现在带有边框:1px纯黑色;)的大小调整为2px,但可以解决此问题。答案提供了一种调整大小的方法,但它近似了,从而导致了新的大小,保持填充并看起来不自然和丑陋。

2 个答案:

答案 0 :(得分:0)

您可以使用export class DashComponent { /** Based on the screen size, switch from standard to one column per row */ cards = this.breakpointObserver.observe(Breakpoints.Handset).pipe( map(({ matches }) => { if (matches) { return [ { title: 'Data Monitoring', imgUrl: './assets/data.png', cols: 1, rows: 1, border: '1px double purple' }, { title: 'New Customer Onboarding', imgUrl: 'assets/customer.png' ,cols: 1, rows: 1, border: '1px double yellow' }, { title: 'Process PO', imgUrl: 'assets/process.png' ,cols: 1, rows: 1,border: '1px double skyblue' }, { title: 'Portal Scrapping',imgUrl: 'assets/portal.png' , cols: 1, rows: 1, border: '1px double red' } ]; } return [ { title: 'Data Monitoring', img: 'assets/data.png', cols: 1, rows: 1, border: '3px double purple' }, { title: 'New Customer Onboarding', img: 'assets/customer.png' ,cols: 1, rows: 1, border: '3px double yellow' }, { title: 'Process PO', img: 'assets/process.png' ,cols: 1, rows: 1,border: '3px double skyblue' }, { title: 'Portal Scrapping',img: 'assets/portal.png' , cols: 1, rows: 1,border: '3px double red' } ]; }) ); constructor(private breakpointObserver: BreakpointObserver) {} } 来检索它,对于该btn的设置宽度,您也不需要offsetWidth: 更新:添加了更改按钮字体大小的功能。

toString
function resizeButton() {
        var btn = document.getElementById('btn-resize-me');
        alert(parseInt(btn.offsetWidth)); 
        btn.style.width = (parseInt(btn.offsetWidth) - 20)+"px";  btn.style.fontSize = "12px";
 alert(parseInt(btn.style.width)); 
    }
#btn-resize-me {
    background-color: #F3F2F1;
    border: 1ox solid gray;;
    color: black;
    padding: 7px 12px 7px;
    text-align: center;
    text-decoration: none;
    display: block;
    font-size: 20px;
    float: left;
    height: 100%;
    width:auto;
}

答案 1 :(得分:0)

function resizeButton() {
    var btn = document.getElementById('btn-resize-me');
    alert(btn.offsetWidth); // alerts 
    btn.style.width = Math.max(btn.offsetWidth - 20, 0) + "px"; // works
    //the width is reduced by about 20, until it can't
}
<button id="btn-resize-me" onClick="resizeButton();" style="width: auto; overflow: hidden;">Some Text</button>

相关问题