简体   繁体   English

检查innerHTML是否超过父级的宽度或高度

[英]Checking if innerHTML exceeds width or height of parent

I have a parent div with a fixed width and a fixed height. 我有一个固定宽度和高度的父div。

The contents how ever might exceed this, so I am wondering is there a way in Javascript to calculate if the content exceeds the fixed dimensions? 内容可能会超出此范围,所以我想知道Javascript中是否有一种方法可以计算内容是否超出固定范围?

An example would be like this: 一个例子是这样的:

<div style="width:20px;height:20px;overflow-x:hidden;overflow-y:hidden;">

 A sentence that exceeds the width!

</div>

In the above case it does exceed the width. 在上述情况下,它确实超过了宽度。 How would this be achieved in Javascript? 用Javascript如何实现?

make a parent for your content: 为您的内容做父母:

<div style="width:20px;height:20px;overflow-x:hidden;overflow-y:hidden;">
 <div id="parent">
 A sentence that exceeds the width!

</div>
</div>

now you can get width and height of the parent and compare it with your main div: 现在您可以获取父级的宽度和高度并将其与主div进行比较:

var h = document.getElementById("parent").offsetHeight;
var w = document.getElementById("parent").offsetWidth;

You can use DOM properties of the div and text nodes. 您可以使用div和text节点的DOM属性 If you can wrap the text in a <span> element, it seems like it will be easier to work with the dimension properties. 如果可以将文本包装在<span>元素中,则似乎可以更轻松地使用尺寸属性。

html html

<div id="container">
  <span>A sentence that exceeds the width!</span>
</div>

css 的CSS

div {
    width:50px;
    overflow:hidden;
    white-space: nowrap;
}

js JS

var cont = document.getElementById('container');
var spn = cont.getElementsByTagName('span')[0];
//alert(cont.clientWidth);
//alert(spn.offsetWidth);

if(spn.offsetWidth > cont.clientWidth) {
    alert("content exceeds width of parent div");
}

http://jsfiddle.net/Bn2Uc/2/ http://jsfiddle.net/Bn2Uc/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM