javascript - 如何使用javaScript将文本高度调整为div

标签 javascript html css

我在街区有一些文章。他们中的一些人像图片一样在他们的中间切开:

enter image description here

我尝试使用下面的函数来解决这个问题,但它仍然不起作用。

const setSameHeightToAll = function() {
    const all = document.querySelectorAll('.text_blog')
    let maxHeight = 0
    var length = all.length
    for (var i = 0; i < length; i++) {
      if (all[i].getBoundingClientRect().height > maxHeight) {
        maxHeight = all[i].getBoundingClientRect().height
      }
    }

    for (var j = 0; j < length; j++) {
      all[j].setAttribute('style', 'height:' + maxHeight + 'px')
    }
}


在 html 中:(这是 pug.js)

.text_blog
   != post.content.full
   p.read_more 
   a(href='/blog/'+post.key) leia mais >>

这是CSS:


.text_blog {
  overflow: hidden;
  height: 112px;
}

如何更改我的函数以使其正常工作。

最佳答案

您在 JavaScript 代码中将最大高度设置为 0。

不知道代码的完整上下文,因为您只发布了 javascript 部分,您可能对所有“.text_blog”元素使用恒定高度或使用

CSS
.text_blog{
  height: auto;
  overflow: scroll;
}

JAVASCRIPT
const setSameHeightToAll = function() {
    const all = document.querySelectorAll('.text_blog')
    //GET HEIGHT OF FIRST ELEMENT AND MAKE IT UNIFORM
    let maxHeight = all.firstElementChild.offsetHeight;
    //SET CONSTANT HEIGHT
    let maxHeight = '500px';
    var length = all.length;

    for (var i = 0; i < length; i++) {
      all[i].setAttribute('style', 'height:' + maxHeight + 'px')
    }
}

您还忘记包含结尾的 ';'在一些行的末尾。

关于javascript - 如何使用javaScript将文本高度调整为div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57182254/

相关文章:

javascript - 从数组中删除一个对象?

html - bootstrap 2.3.1 段落旁边的图像

javascript - 悬停方向根据容器大小

html - img float 影响居中

javascript - 不使用 PHP 的 reCaptcha

javascript - Rails 渲染 js 文件但无法执行

javascript - 循环遍历javascript中动态添加的输入类型单选列表的列表

jquery - 设置已检查 p :selectOneRadio item 的 td

html - 当屏幕宽度小于 X 时是否有可能禁用继承?

javascript - 替换 node.js 中 XML Node 中的文本