【问题标题】:Getting the height of a div, but not in pixels获取 div 的高度,但不是以像素为单位
【发布时间】:2011-11-22 16:53:56
【问题描述】:

感谢您对此进行调查。 基本上,我想要做的是获取 div 的高度(在我的 style.css 中设置为 100%,因此它应该可以在任何设备上调整大小),以便我可以打印数字 1-任何数字。

例如,如果窗口很小,它会打印出数字 1-45,如果是智能手机浏览器,那么数字将缩小到 1-10。

目前是这样的:

<div id="line_numbers">
        <script type="text/javascript">
            var i=0;
            var div_height=(document.getElementById('line_numbers').offsetHeight)/ getElementsByTagName("p").style.fontSize();

             while (i < div_height) { //if i is less that the height
                i++; //then increase its number
                document.write("<p>" + i + "</p>"); //and print out the number and new line (<p>)
            }
        </script><!--end of iteration script-->
</div><!--end of line numbers-->

我理解高度 var 的计算是错误的,但我希望你理解逻辑:得到 div 的高度并为每个

(每个打印的数字)是5px,每个数字的字体高度,我可以将高度除以字体大小+10px(上下填充)。 当我尝试打印出 div_height 变量时,什么也没有发生,我有点困惑。

再次感谢您抽出宝贵时间。

布拉吉-布拉

【问题讨论】:

  • 看来你的JS代码是在页面还没有完全布局的时候执行的,所以line_numbers div的高度为零。尝试在 onload 事件处理程序中执行您的代码。如果没有解决您的问题,请将您的代码放入jsfiddle,方便大家帮到您
  • 不应该getElementsByTagName("p").style.fontSize();getElementsByTagName("p")[0].style.fontSize();
  • 谢谢你们两个:)我明天会尝试这样做! :)

标签: javascript html css


【解决方案1】:

看起来你得到了你想要的,但这里有一个提示来补充上面的答案:考虑使用element.style.lineHeight而不是element.style.fontSize,因为只有前者乘以行数会给你div 的实际高度,(或给定的准确行数 height \ line-height)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多