使用JS根据内容更改div高度

时间:2018-11-12 12:18:57

标签: javascript arrays for-loop dynamic height

我正在尝试创建一个简单的横幅,该横幅可以根据标题和副标题中的文本量来更改高度。

因此,我们有两个如上所述的元素。

标题1和标题2(副标题)。

如果标题超过1行,副标题为1行,则横幅的高度为258px 如果标题超过2行,副标题为1行,则横幅的高度为314px 如果标题超过3行而副标题为1行,则横幅的高度将为370px

还有这种情况: 如果标题超过1行,副标题为2行,则横幅的高度为298px 如果标题超过2行而副标题为2行,则横幅的高度将为354px 如果标题超过3行,副标题为2行,则横幅的高度将为405px

所以我知道每种情况下高度总是增加56px。

这是到目前为止所做的事情:

var hl11sub = 258; //这是最小横幅的高度     var hl21sub = 314; // 56px是头部和子组合每次变大时高度增加多少     var hl31sub = 370;

var hl12sub = 298; // This is the height of the banner when there is 1hl and 2 subheadlines
var hl22sub = 354; // This is the height of the banner when there is 2hl and 2 subheadlines
var hl32sub = 405; // This is the height of the banner when there is 3hl and 2 subheadlines

var hLFontSizeCSS = window.getComputedStyle(headlineText, null).getPropertyValue("font-size");
var hL2FontSizeCSS = window.getComputedStyle(headline2text, null).getPropertyValue("font-size");
var bannerHeightCSS = window.getComputedStyle(banner, null).getPropertyValue("height");
var headlineHeight = headlineText.offsetHeight;
var hL2HeadHeight = headline2text.offsetHeight;

var headHeight = headlineText.style.lineHeight = parseInt(hLFontSizeCSS) + 10 + "px";
var hL2Height = headline2text.style.lineHeight = parseInt(hL2FontSizeCSS) + 10 + "px";

// Text Height values
var hL1LineHeight = parseInt(headHeight); // 8 is line height & padding
var hL2LinesHeight = parseInt(headHeight)*2;
var hL3LinesHeight = parseInt(headHeight)*3;

// HL2 height values
var hL2TextOver1LineHeight = parseInt(hL2Height); // 8 is line height & padding
var hL2TextOver2LineHeight = parseInt(hL2Height)*2;

if(headlineHeight == hL1LineHeight && hL2HeadHeight == hL2TextOver1LineHeight){
  banner.style.height = hl11sub + "px";
}
else if(headlineHeight == hL2LinesHeight && hL2HeadHeight == hL2TextOver1LineHeight){
  banner.style.height = hl21sub + "px";
}
else if(headlineHeight >= hL3LinesHeight && hL2HeadHeight == hL2TextOver1LineHeight){
  banner.style.height = hl31sub + "px";
}
else if(headlineHeight == hL1LineHeight && hL2HeadHeight == hL2TextOver2LineHeight){
  // Single headline with 2 lines sub
  banner.style.height = hl12sub + "px";
}
else if(headlineHeight == hL2LinesHeight && hL2HeadHeight == hL2TextOver2LineHeight){
  // 2 headlines with 2 lines sub
  banner.style.height = hl22sub + "px";
}
else if(headlineHeight == hL3LinesHeight && hL2HeadHeight == hL2TextOver2LineHeight){
  banner.style.height = hl32sub + "px";
  // 3 headlines with 2 lines sub

}

我仍然对JS还是陌生的,所以我已经写了这是我能想到的最简单的方法,它可以正常工作,但肯定是一种手动的编写方法,并希望获得一些改进建议(以一种可能的方式可以使用不同的字体大小?)。

这里是CP-https://codepen.io/nolimit966/pen/jQrygg?editors=1111

任何帮助将不胜感激。

0 个答案:

没有答案