Javascript 如何检测textContent何时溢出其父级

Javascript 如何检测textContent何时溢出其父级,javascript,css,dom-events,whitespace,Javascript,Css,Dom Events,Whitespace,需要: 我需要一个触发器,当一个按钮的文本内容溢出它的按钮宽度 问题: 是否有任何简洁/聪明的方法来检测textContent何时溢出其父项 更新:看来这会解决我的问题 HTML: <div class="container"> <button>a normal button</button> <button>tiny</button> <button class="parent&

需要:
我需要一个触发器,当一个按钮的文本内容溢出它的按钮宽度

问题:
是否有任何简洁/聪明的方法来检测textContent何时溢出其父项

更新:看来这会解决我的问题

HTML:

<div class="container">
   <button>a normal button</button>
   <button>tiny</button>
   <button class="parent">
     <div class="child">a rhhh, really wide button lskdfjlasdkfj lksjd flaksjd flaskdjf lkj</div>
   </button>
</div>
.container {
  display: inline-grid;
  grid-template-columns: 1fr 1fr 1fr;

  grid-column-gap: 20px;
}
.parent {
    overflow: hidden;
}
button {
  white-space: nowrap;
}
const child = document.querySelector('.child');
console.log(child.scrollWidth, 'child');

const parent = document.querySelector('.parent');
console.log(parent.clientWidth,'parent');
JS:

<div class="container">
   <button>a normal button</button>
   <button>tiny</button>
   <button class="parent">
     <div class="child">a rhhh, really wide button lskdfjlasdkfj lksjd flaksjd flaskdjf lkj</div>
   </button>
</div>
.container {
  display: inline-grid;
  grid-template-columns: 1fr 1fr 1fr;

  grid-column-gap: 20px;
}
.parent {
    overflow: hidden;
}
button {
  white-space: nowrap;
}
const child = document.querySelector('.child');
console.log(child.scrollWidth, 'child');

const parent = document.querySelector('.parent');
console.log(parent.clientWidth,'parent');
正常:

触发:

注:
我不能依赖滚动条。(更新了sorta use scrollbars)

不确定这有多可靠,而且布局混乱,但它对我很有效:

function isButtonOverflowing ( button ) {
    var oldHeight = button.offsetHeight;
    button.style.whiteSpace = 'normal';
    var newHeight = button.offsetHeight;
    button.style.whiteSpace = '';
    return oldHeight !== newHeight;
}

受我在评论中为您提供的链接启发,以下是一个工作片段:

$(“按钮”)。每个(函数(){
如果($(此)[0].scrollWidth>$(此).innerWidth(){
log(“溢出!”);
}否则{
log(“没关系。”);
}
});
.container{
显示:内联网格;
网格模板柱:1fr 1fr 1fr;
栅柱间隙:20px;
}
钮扣{
空白:nowrap;
/*为测试添加*/
宽度:120px;
}

普通按钮
微小的
一个很宽的按钮

同样的代码:p您想在调整大小时检测到这一点吗?也许其中一个会有帮助:我找到了这个主题,它可能会有所帮助: