【问题标题】:Grab random line from multi-line <p>aragraph with jquery? [closed]用jquery从多行<paragraph中抓取随机行? [关闭]
【发布时间】:2015-06-01 07:29:34
【问题描述】:

是否可以从包含长篇故事的段落中随机抽取一行?

【问题讨论】:

  • 当然,您只需编写一些代码即可。

标签: javascript jquery


【解决方案1】:

function showLines() {
  var lines = getLines();
  
    lines = lines.map(function(line) {
      return line.map(function(span) {
        return span.innerText;
      }).join(' ')
    });
  return lines;
}

function splitLines() {
  var p = document.getElementsByTagName('p')[0];
  p.innerHTML = p.innerText.split(/\s/).map(function(word) {
    return '<span>' + word + '</span>'
  }).join(' ');
}



function getLines() {
  var lines = [];
  var line;
  var p = document.getElementsByTagName('p')[0];
  var words = p.getElementsByTagName('span');
  var lastTop;
  for (var i = 0; i < words.length; i++) {
    var word = words[i];
    if (word.offsetTop != lastTop) {
      lastTop = word.offsetTop;
      line = [];
      lines.push(line);
    }
    line.push(word);
  }
  return lines;
}
splitLines();
var lines = showLines();
console.log(lines);
var randomLine = lines[Math.floor(Math.random()*lines.length)];
console.log(randomLine);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<p id="para"> This is a test. Is it? Yes, it is indeed! 
You might ask, is this a sentence? To which I would reply 
with a resounding "YES"!!!This is a test. Is it? Yes, it is indeed! 
You might ask, is this a sentence? To which I would reply 
with a resounding "YES"!!!</p>

How to split an HTML paragraph up into its lines of text with JavaScriptGet random item from JavaScript array

【讨论】:

  • 太棒了!这行得通!
  • @jibly,我以前的答案有一个错误,因为它是按句子而不是按行拆分的。查看我更新的答案,它按实际行拆分然后得到一个随机行
猜你喜欢
  • 2012-11-03
  • 2015-01-06
  • 1970-01-01
  • 1970-01-01
  • 2013-06-21
  • 2022-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多