JS for循环+ if语句:在有条件地更新文本节点时捕获最后一次出现

问题描述 投票:1回答:1

我有一个包含多个段落的数组,这些段落将放置在一个容器中,直到该容器»满«。不适用于该容器的物品应放入单独的容器中。

我的解决方案在大多数情况下都可以正常工作,但有一个“美容”错误,我想修复该错误。我的方法是声明将要放置文本的容器的最大高度(由于为空,因此开头为0px)。此最大高度等于包装容器的元素的高度,该高度通过CSS设置。

然后我通过更新text node将内容放入第一个容器的nodeValue中。在每次迭代之前,都要检查容器的高度,只要它不比包裹它的父容器高,就放置内容。第一个容器“装满”(=它的高度等于其父代的高度)后,其余内容将放入单独的容器中。

我不能简单地放置整个段落,因为如果放置在第一个容器内的最后一段足够长以填充多行(当然,这取决于容器/父项的宽度),则这些行仍将结束于第一行容器并切断。因此,我要遍历每个段落的每个单词,每次nodeValue更新时都要检查高度。

这一切都按预期工作,请参见附件。

唯一剩下的问题是第一个容器内的最后一行文本只有一个字长。我当然知道会发生这种情况,因为一旦用这个词更新nodeValue时,容器的高度就会被识别为太高而无法容纳更多内容,并且脚本会移至下一个容器。

是否有办法“抓住”最后一个单词并确保它也被放入第二个容器中?或者,也可以正确地填充第一个容器的最后一行,但是我认为那比较复杂。感谢任何建议。

// Utilities
function update_NodeContent(newContent, container) {
  var nodeContent_old = container.childNodes[0].nodeValue;
  var nodeContent_add = newContent + " ";
  var nodeContent_new = nodeContent_old + nodeContent_add;
  container.childNodes[0].nodeValue = nodeContent_new;
}

// Variables
var cellHeight = $("#cell1").height();

// Content
var content = [
  "The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex!",

  "Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz.",

  "How quickly daft jumping zebras vex. Two driven jocks help fax my big quiz. Quick, Baz, get my woven flax jodhpurs! »Now fax quiz Jack!« my brave ghost pled. Five quacking zephyrs jolt my wax bed.",

  "Flummoxed by job, kvetching W. zaps Iraq. Cozy sphinx waves quart jug of bad milk. A very bad quack might jinx zippy fowls. Few quips galvanized the mock jury box. Quick brown dogs jump over the lazy fox."
]


function placeText() {
  while (content.length) {
    var node = document.createTextNode("");
    $("#cell1 .container").append(node);
    //
    var content_words = content[0].split(" ");
    for (var i = 0; i < content_words.length; i++) {
      //
      var textBlockHeight = $("#cell1 .container").height();
      if (textBlockHeight < cellHeight) {
        update_NodeContent(content_words[i], $('#cell1 .container')[0]);
      } else {
        update_NodeContent(content_words[i], $('#cell2 .container')[0]);
      }
    }
    //
    var itemtoRemove = content[0];
    content.shift();
  }
}

// Execution
placeText();
:root {
  --height_line_single: 19px;
  --height_textBlock: calc(var(--height_line_single) * 14);
}

body {
  font-size: 16px;
  line-height: 1.2;
}

p {
  margin: 0 0 1rem 0;
}

p.noMargin {
  margin: 0;
}

.article {
  width: 90vw;
}

.text-block {
  height: var(--height_textBlock);
  overflow: hidden;
  background: lightgreen;
  margin-bottom: 1rem;
}

#cell1 {
  width: calc(100%/3);
}

#cell2 {
  column-count: 3;
  column-fill: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="article">

  <div id="cell1" class="text-block">
    <div class="container">
    </div>
  </div>

  <div id="cell2" class="text-block">
    <div class="container">
    </div>
  </div>

</div>
javascript loops if-statement conditional-statements textnode
1个回答
0
投票

这是一个可行的例子。如果需要,可以将选择器和高度更改为使用jQuery版本。您尚未完成上面示例中内容的循环,因此我将其留给您添加。

也可以在CodePen上查看此示例:https://codepen.io/edlucas/pen/MWYrybK

// Utilities
function update_NodeContent(newContent, container) {
    // Ensure that we start with an empty string
    var nodeContent_old = container.innerHTML ? container.innerHTML : '';
    container.innerHTML = nodeContent_old + newContent + " ";
}

// Content
var content = [
    "The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex!",
    "Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz.",
    "How quickly daft jumping zebras vex. Two driven jocks help fax my big quiz. Quick, Baz, get my woven flax jodhpurs! »Now fax quiz Jack!« my brave ghost pled. Five quacking zephyrs jolt my wax bed.",
    "Flummoxed by job, kvetching W. zaps Iraq. Cozy sphinx waves quart jug of bad milk. A very bad quack might jinx zippy fowls. Few quips galvanized the mock jury box. Quick brown dogs jump over the lazy fox."
]

var containerHeight = document.querySelector('#cell1').clientHeight;

function placeText() {
    if (content.length) {
        var content_words = content[0].split(" ");
        var holdContent = "";
        var useSecondContainer = false;
        var $textBlock1 = document.querySelector('#cell1 .container');
        var $textBlock2 = document.querySelector('#cell2 .container');
        var textBlockHeight = 0;
        var word = '';

        for (var i = 0; i < content_words.length; i++) {
            word = content_words[i];

            // Ensure that we have a word to display
            if (word && word.trim()) {
                textBlockHeight = $textBlock1.clientHeight;

                // If we have not already exceeded the first container
                if (textBlockHeight <= containerHeight && !useSecondContainer) {
                    // Add to first container
                    holdContent = $textBlock1.innerHTML;
                    update_NodeContent(word, $textBlock1);

                    // If we exceed the height with this addition, restore the contents to the
                    // last state and add this word to the second container
                    if ($textBlock1.clientHeight > containerHeight) {
                        // Restore last good content
                        $textBlock1.innerHTML = holdContent;

                        // Add to the second container                              
                        useSecondContainer = true;
                        update_NodeContent(word, $textBlock2);
                    }
                } else {
                    // Add to the second container
                    update_NodeContent(word, $textBlock2);
                }
            }
        }
    }
}
// Execution
placeText();
:root {
  --height_line_single: 19px;
  --height_textBlock: calc(var(--height_line_single) * 2);
}

body {
  font-size: 16px;
  line-height: 1.2;
}

p {
  margin: 0 0 1rem 0;
}

p.noMargin {
  margin: 0;
}

.article {
  width: 90vw;
}

.text-block {
  height: var(--height_textBlock);
  overflow: hidden;
  background: lightgreen;
  margin-bottom: 1rem;
}

#cell1 {
  width: calc(100%/3);
}

#cell2 {
  column-count: 3;
  column-fill: auto;
}
<div class="article">

  <div id="cell1" class="text-block">
    <div class="container">
    </div>
  </div>

  <div id="cell2" class="text-block">
    <div class="container">
    </div>
  </div>

</div>
© www.soinside.com 2019 - 2024. All rights reserved.