简体   繁体   English

查找包含文本的元素的高度

[英]Find height of element containing text

I have a box with fixed width (800px) that is filled with contents from nicEdit. 我有一个固定宽度(800px)的盒子,里面装着nicEdit的内容。

I need to know the height of the contents that are put inside the box, if I count the number of rows it will not work with long texts or with images or different font sizes... 我需要知道放在盒子里的内容的高度,如果我计算行数,那么它对于长文本,图像或不同字体大小将不起作用...

I need to find the height to set the box with an height that will not show scrollbars and will not be higher than the content. 我需要找到高度以将框设置为不会显示滚动条且不会高于内容的高度。

<div style="width: 800px; overflow: hidden"><?= $contentbyuser; ?></div>

This "page" will be shown into an iFrame with a code like: 该“页面”将显示在iFrame中,其代码如下:

<iframe style="width: 800px;height:???px;" src="page.php"></iframe>

How can I find the height to set to the iframe with javascript and/or jQuery? 如何找到要使用JavaScript和/或jQuery设置为iframe的高度?

You can create a dummy element, insert the HTML into it, and then check its height. 您可以创建一个虚拟元素,将HTML插入其中,然后检查其高度。

//create dummy
var $dummy = $('<div />').css({ position : 'absolute', left : -9999, width : 800 }).html(randomTextandImages);

//add dummy to the DOM
$("body").append($dummy);

//get the height of the dummy
var theHeight = $dummy.height();

//at this point we can remove the dummy from the DOM
$dummy.remove();

//set the height of the iframe
$("iframe").height(theHeight);

Be aware that the dummy element should have the same CSS applied to it as your regular container, so that it will render the same. 请注意,dummy元素应具有与常规容器相同的CSS,以便其呈现相同的样式。 Font properties are particularly important (eg font-size, font-weight, line-height, etc.). 字体属性特别重要(例如,字体大小,字体粗细,行高等)。

Setting the position to absolute and giving a large negative left property means this will occur off-screen, so the user won't see it happen. 将位置设置为absolute并提供较大的负左属性意味着这将在屏幕外发生,因此用户不会看到它发生。

Also, I can't remember if I'd had an issue with this in the past, but if you're getting a height of zero then the code that gets the height of the dummy should be put in a short timeout so the dummy can render before getting its height. 另外,我不记得以前是否遇到过这个问题,但是如果您将高度设置为零,则应该将获得假人高度的代码放入较短的超时时间,因此假人可以在获得高度之前进行渲染。

Set the height of the div to be automatic based on the content. 根据内容将div的高度设置为自动。 Then you can do this in your JavaScript: 然后,您可以在JavaScript中执行此操作:

$("div").html(randomTextandImages);
var height = $('div').height();        // Give this to whoever will be using the iframe

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

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