【问题标题】:DIV height can't be resized with JavaScript无法使用 JavaScript 调整 DIV 高度
【发布时间】:2017-09-12 06:38:23
【问题描述】:

我想用 JavaScript 调整 div 元素的高度。

从这个 div,我正在读取高度

<div class="pages" id="alles">

这是我要调整大小的 div(可以不止一个)

<div class="content-block" name="maxhoehe">

这是我的 JavaScript 代码:

var sh = document.getElementById("alles").offsetHeight;
         document.getElementsByName("maxhoehe").style.height = sh-180 + "px";

在 chrome 中,我会收到以下错误:

Uncaught TypeError: Cannot set property 'height' of undefined

我不知道为什么?

【问题讨论】:

    标签: javascript jquery html css resize


    【解决方案1】:

    Document#getElementsByName 方法返回一个元素集合,因此您需要通过其索引获取第一个元素,否则 style 属性将是 undefined(nodelist 没有任何样式属性)。

    document.getElementsByName("maxhoehe")[0].style.height = (sh - 180) + "px";
    

    要全部更新,请遍历元素并更新属性。

    var elements = document.getElementsByName("maxhoehe");
    
    // in latest browser use Array.from(elements)
    [].slice.call(elements).forEach(function(ele){
       ele.style.height = (sh - 180) + "px"
    }); 
    

    【讨论】:

    • 看起来不错。谢谢。但只有第一个 div 会被调整大小。不是其他的..
    【解决方案2】:

    如果您想使用 JQuery,请使用以下代码。

    $('#change').on('click', function(){
      $('.content-block').height($('.pages').height());
    });
    div{
    border: 1px solid red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="pages" id="alles">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
    <div class="content-block" name="maxhoehe">sad</div>
    <input type="button" value="change" id="change" >

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-22
      • 2013-01-19
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 2013-10-01
      • 2013-11-12
      • 2014-04-14
      相关资源
      最近更新 更多