复杂的JavaScript,如何连接字母以正确的方式组成一个单词,同时打开窗口

7vux5j2d  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(82)

bounty将在5天内到期。回答此问题可获得+50声望奖励。Xrayman希望引起更多关注此问题:一个完全有效且响应迅速的解决方案

我的问题是,每个字母都在一个跨度内,并作为一个单元进行管理,因此,当删除窗口单词时,可能会以错误的方式截断,因此组成单词的字母可能会在不同的行中。
我该如何解决?
我知道脚本应该比这个更复杂,但我不知道如何做到这一点。

$(document).ready(function() {
  /*
   * Main variables
   */
  var content = [{
    title: "Hi! Mate.",
    desc: "Welcome to my alphabet soup demo!"
  }, {
    title: "Lorem ipsum",
    desc: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  }, {
    title: "dolor sit amet",
    desc: "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
  }, {
    title: "Grouping example",
    desc: [
      ["<u>Grouped text</u>"], " separate text".split("")
    ]
  }];
  var currentPage = 0;
  //generate content
  for (var i = 0; i < content.length; i++) {
    //split content letters to array
    for (var obj in content[i]) {
      //if string
      if (typeof content[i][obj] === "string") {
        content[i][obj] = content[i][obj].split("");
        continue;
      }
      //if array (grouped text)
      else if (typeof content[i][obj] === "object") {
        var toPush = [];
        for (var j = 0; j < content[i][obj].length; j++) {
          for (var k = 0; k < content[i][obj][j].length; k++) {
            toPush.push(content[i][obj][j][k]);
          }
        }
        content[i][obj] = toPush;
      }
    }
    //set text to 
    $("#segments").append("<div class=\"letters-wrap mutable\"><div class=\"soup-title\"></div><div class=\"soup-desc\"></div></div>");
    setText();
    //clone to data
    $("#segments").append("<div class=\"letters-wrap position-data\"><div class=\"soup-title\"></div><div class=\"soup-desc\"></div></div>");
    setText();
  }
  //initial arrangement
  arrangeCurrentPage();
  scrambleOthers();
  /*
   * Event handlers
   */
  $(window).resize(function() {
    arrangeCurrentPage();
    scrambleOthers();
  });
  $("#soup-prev").hide();
  $("#soup-prev").click(function() {
    $("#soup-next").show();
    currentPage--;
    if (currentPage === 0) {
      $("#soup-prev").hide();
    }
    arrangeCurrentPage();
    scrambleOthers();
  });
  $("#soup-next").click(function() {
    $("#soup-prev").show();
    currentPage++;
    if (currentPage === content.length - 1) {
      $("#soup-next").hide();
    }
    arrangeCurrentPage();
    scrambleOthers();
  });
  /*
   * Functions
   */
  function arrangeCurrentPage() {
    for (var i = 0; i < content[currentPage].title.length; i++) {
      $(".mutable:eq(" + currentPage + ") > .soup-title > .letter").eq(i).css({
        left: $(".position-data:eq(" + currentPage + ") > .soup-title > .letter").eq(i).offset().left + "px",
        top: $(".position-data:eq(" + currentPage + ") > .soup-title > .letter").eq(i).offset().top + "px",
        color: "#111",
        zIndex: 9001
      });
    }
    for (var i = 0; i < content[currentPage].desc.length; i++) {
      $(".mutable:eq(" + currentPage + ") > .soup-desc > .letter").eq(i).css({
        left: $(".position-data:eq(" + currentPage + ") > .soup-desc > .letter").eq(i).offset().left + "px",
        top: $(".position-data:eq(" + currentPage + ") > .soup-desc > .letter").eq(i).offset().top + "px",
        color: "#111",
        zIndex: 9001
      });
    }
  }

  function setText() {
    var j;
    for (j = 0; j < content[i].title.length; j++) {
      $(".soup-title").last().append("<span class=\"letter\">" + content[i].title[j] + "</span>");
    }
    for (j = 0; j < content[i].desc.length; j++) {
      $(".soup-desc").last().append("<span class=\"letter\">" + content[i].desc[j] + "</span>");
    }
  }

  function scrambleOthers() {
    for (var i = 0; i < content.length; i++) {
      //don't scramble currentPage
      if (currentPage === i)
        continue;
      var parts = [
        ["title", ".soup-title"],
        ["desc", ".soup-desc"]
      ];
      //apply to .title h1s and .desc ps
      for (var j = 0; j < parts.length; j++) {
        for (var k = 0; k < content[i][parts[j][0]].length; k++) {
          //define random position on screen
          var randLeft = Math.floor(Math.random() * $(window).width());
          var randTop = Math.floor(Math.random() * $(window).height());
          //defining boundaries
          var offset = $(".position-data").eq(currentPage).offset();
          var bounds = {
            left: offset.left,
            top: offset.top,
            right: $(window).width() - offset.left,
            bottom: $(window).height() - offset.top
          };
          var middleX = bounds.left + $(".position-data").eq(currentPage).width() / 2;
          var middleY = bounds.top + $(".position-data").eq(currentPage).height() / 2;
          //finally, apply all the scrambles
          $(".mutable:eq(" + i + ") > " + parts[j][1] + " > .letter").eq(k).css({
            left: randLeft,
            top: randTop,
            color: "#DDD",
            zIndex: "initial"
          });
        }
      }
    }
  }
});
html,
body {
  width: 100%;
  height: 100%;
  background-color: #eeeeee;
  color: #111111;
  text-align: center;
  font-family: 'Open Sans', sans-serif;
}

#soup-nav {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 32px;
  z-index: 9002;
  font-size: 64px;
}

.soup-title {
  font-size: 32px;
}

.soup-desc {
  font-size: 16px;
}

#soup-container {
  width: 100%;
  height: 100%;
  min-width: 320px;
  min-height: 480px;
  position: relative;
}

.letters-wrap {
  position: absolute;
  overflow: hidden;
  display: inline-block;
}

.letters-wrap.mutable {
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

.letters-wrap.mutable .letter {
  position: absolute;
  left: 0;
  top: 0;
  transition: left 2s, top 2s, color 2s;
  color: #aaaaaa;
}

.letters-wrap.mutable .letter.active {
  color: #111111;
  z-index: 9001;
}

.letters-wrap.position-data {
  top: 50%;
  left: 50%;
  /*opacity: 0.1;
   */
  visibility: hidden;
  transform: translate(-50%, -50%);
}

.segment {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.letter {
  /*display: inline-block;
   */
  white-space: pre;
}

button {
  z-index: 9001;
  position: relative;
}
<div id="loader"></div>
<div id="soup-container">
  <div id="segments"></div>
  <div id="soup-nav">
    <span id="soup-prev"><i class="lni-arrow-left" aria-hidden="true"><-</i></span>
    <span id="soup-next"><i class="lni-arrow-right" aria-hidden="true">-></i></span>
  </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
qncylg1j

qncylg1j1#

既然你已经在使用JavaScript进行布局操作了,你可以计算容器的宽度,并通过编程来确定何时断开线条。下面是我的尝试,我添加了函数arrangeLetters()

$(document).ready(function() {
  var content = [{
    title: "Hi! Mate.",
    desc: "Welcome to my alphabet soup demo!"
  }, {
    title: "Lorem ipsum",
    desc: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  }, {
    title: "dolor sit amet",
    desc: "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
  }, {
    title: "Grouping example",
    desc: [
      ["<u>Grouped text</u>"], " separate text".split("")
    ]
  }];
  var currentPage = 0;
  for (var i = 0; i < content.length; i++) {
    for (var obj in content[i]) {
      if (typeof content[i][obj] === "string") {
        content[i][obj] = content[i][obj].split("");
        continue;
      } else if (typeof content[i][obj] === "object") {
        var toPush = [];
        for (var j = 0; j < content[i][obj].length; j++) {
          for (var k = 0; k < content[i][obj][j].length; k++) {
            toPush.push(content[i][obj][j][k]);
          }
        }
        content[i][obj] = toPush;
      }
    }
    $("#segments").append("<div class=\"letters-wrap mutable\"><div class=\"soup-title\"></div><div class=\"soup-desc\"></div></div>");
    setText();
    //clone to data
    $("#segments").append("<div class=\"letters-wrap position-data\"><div class=\"soup-title\"></div><div class=\"soup-desc\"></div></div>");
    setText();
  }
  arrangeCurrentPage();
  scrambleOthers();
  $(window).resize(function() {
    arrangeCurrentPage();
    scrambleOthers();
  });
  $("#soup-prev").hide();
  $("#soup-prev").click(function() {
    $("#soup-next").show();
    currentPage--;
    if (currentPage === 0) {
      $("#soup-prev").hide();
    }
    arrangeCurrentPage();
    scrambleOthers();
    arrangeLetters();
  });
  $("#soup-next").click(function() {
    $("#soup-prev").show();
    currentPage++;
    if (currentPage === content.length - 1) {
      $("#soup-next").hide();
    }
    arrangeCurrentPage();
    scrambleOthers();
    arrangeLetters();
  });

  function arrangeCurrentPage() {
    for (var i = 0; i < content[currentPage].title.length; i++) {
      $(".mutable:eq(" + currentPage + ") > .soup-title > .letter").eq(i).css({
        left: $(".position-data:eq(" + currentPage + ") > .soup-title > .letter").eq(i).offset().left + "px",
        top: $(".position-data:eq(" + currentPage + ") > .soup-title > .letter").eq(i).offset().top + "px",
        color: "#111",
        zIndex: 9001
      });
    }
    for (var i = 0; i < content[currentPage].desc.length; i++) {
      $(".mutable:eq(" + currentPage + ") > .soup-desc > .letter").eq(i).css({
        left: $(".position-data:eq(" + currentPage + ") > .soup-desc > .letter").eq(i).offset().left + "px",
        top: $(".position-data:eq(" + currentPage + ") > .soup-desc > .letter").eq(i).offset().top + "px",
        color: "#111",
        zIndex: 9001
      });
    }
  }

  function setText() {
    var j;
    for (j = 0; j < content[i].title.length; j++) {
      $(".soup-title").last().append("<span class=\"letter\">" + content[i].title[j] + "</span>");
    }
    for (j = 0; j < content[i].desc.length; j++) {
      $(".soup-desc").last().append("<span class=\"letter\">" + content[i].desc[j] + "</span>");
    }
  }

  function scrambleOthers() {
    for (var i = 0; i < content.length; i++) {
      if (currentPage === i)
        continue;
      var parts = [
        ["title", ".soup-title"],
        ["desc", ".soup-desc"]
      ];
      for (var j = 0; j < parts.length; j++) {
        for (var k = 0; k < content[i][parts[j][0]].length; k++) {
          var randLeft = Math.floor(Math.random() * $(window).width());
          var randTop = Math.floor(Math.random() * $(window).height());
          var offset = $(".position-data").eq(currentPage).offset();
          var bounds = {
            left: offset.left,
            top: offset.top,
            right: $(window).width() - offset.left,
            bottom: $(window).height() - offset.top
          };
          var middleX = bounds.left + $(".position-data").eq(currentPage).width() / 2;
          var middleY = bounds.top + $(".position-data").eq(currentPage).height() / 2;
          $(".mutable:eq(" + i + ") > " + parts[j][1] + " > .letter").eq(k).css({
            left: randLeft,
            top: randTop,
            color: "#DDD",
            zIndex: "initial"
          });
        }
      }
    }
  }

  function arrangeLetters() {
    let container = $("#soup-container");
    let containerWidth = container.width();
    let containerCenter = container.offset().left + containerWidth / 2;
    let titleTop = $(".position-data:eq(" + currentPage + ")").offset().top;
    let titleHeight = arrangeSection("title", titleTop);

    let descriptionTop = titleTop + titleHeight + 20;
    arrangeSection("desc", descriptionTop);

    function arrangeSection(section, currentTop) {
      let maxLineHeight = 0;
      let sectionHeight = 0;
      let currentLineWidth = 0;
      let lineStartIndex = 0;

      $(".mutable:eq(" + currentPage + ") > .soup-" + section + " > .letter").each(function(index) {
        let letterWidth = $(this).outerWidth(true);
        let letterHeight = $(this).outerHeight(true);
        maxLineHeight = Math.max(maxLineHeight, letterHeight);

        if (currentLineWidth + letterWidth > containerWidth) {

          centerLine(lineStartIndex, index - 1, currentLineWidth, currentTop, section);
          currentTop += maxLineHeight;
          sectionHeight += maxLineHeight;
          currentLineWidth = 0;
          lineStartIndex = index;
          maxLineHeight = letterHeight;
        }

        currentLineWidth += letterWidth;
      });

      centerLine(lineStartIndex, $(".mutable:eq(" + currentPage + ") > .soup-" + section + " > .letter").length - 1, currentLineWidth, currentTop, section);
      sectionHeight += maxLineHeight;

      return sectionHeight;
    }

    function centerLine(startIndex, endIndex, lineWidth, currentTop, section) {
      let currentLeft = containerCenter - lineWidth / 2;
      $(".mutable:eq(" + currentPage + ") > .soup-" + section + " > .letter").slice(startIndex, endIndex + 1).each(function() {
        $(this).css({
          top: currentTop + "px",
          left: currentLeft + "px"
        });
        currentLeft += $(this).outerWidth(true);
      });
    }
  }
  arrangeLetters();
});
html,
body {
  width: 100%;
  height: 100%;
  background-color: #eeeeee;
  color: #111111;
  text-align: center;
  font-family: 'Open Sans', sans-serif;
}

#soup-nav {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 32px;
  z-index: 9002;
  font-size: 64px;
}

.soup-title {
  font-size: 32px;
}

.soup-desc {
  font-size: 16px;
}

#soup-container {
  width: 100%;
  height: 100%;
  min-width: 320px;
  min-height: 480px;
  position: relative;
}

.letters-wrap {
  position: absolute;
  overflow: hidden;
  display: inline-block;
}

.letters-wrap.mutable {
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

.letters-wrap.mutable .letter {
  position: absolute;
  left: 0;
  top: 0;
  transition: left 2s, top 2s, color 2s;
  color: #aaaaaa;
}

.letters-wrap.mutable .letter.active {
  color: #111111;
  z-index: 9001;
}

.letters-wrap.position-data {
  top: 50%;
  left: 50%;
  visibility: hidden;
  transform: translate(-50%, -50%);
}

.segment {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.letter {
  white-space: pre;
}

button {
  z-index: 9001;
  position: relative;
}
<div id="loader"></div>
<div id="soup-container">
  <div id="segments"></div>
  <div id="soup-nav">
    <span id="soup-prev"><i class="lni-arrow-left" aria-hidden="true">&lt;&#8722;</i></span>
    <span id="soup-next"><i class="lni-arrow-right" aria-hidden="true">&#8722;&gt;</i></span>
  </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

相关问题