在浏览器中,如何确定哪种换行符适合操作系统?

dav*_*ers 0 javascript dom cross-browser

\n\r\n(或什至\r)换句话说。我很想避免嗅探用户代理字符串。

第一次尝试:

var osLineBreak = (function () {
  var p = document.createElement('p');
  p.innerHTML = '<br>';
  return p.innerText;
}());
Run Code Online (Sandbox Code Playgroud)

不幸的是,Firefox不提供innerText,并且textContent在这种情况下返回空字符串。

第二次尝试:

var osLineBreak = (function () {
  var
    lineBreak,
    body = document.body,
    range = document.createRange(),
    selection = window.getSelection(),
    p = document.createElement('p');

  // we cannot make a selection unless `p` is in the DOM,
  // so ensure that it is not visible when we insert it
  p.style.position = 'absolute';
  p.style.left = '-9999px';
  // Firefox returns the empty string if `innerHTML` is
  // set to "<br>", so include leading and trailing
  // characters
  p.innerHTML = '%<br>%';
  body.appendChild(p);
  // wrap `p` in `range`
  range.selectNodeContents(p);
  // make a selection from `range`
  selection.addRange(range);
  // see how the line break is treated in the selection
  // (provide a sane fallback in case we get the empty string)
  lineBreak = /%(.*)%/.exec(selection.toString())[1] || '\n';
  // revert our fiddlings
  selection.removeAllRanges();
  body.removeChild(p);
  return lineBreak;
}());
Run Code Online (Sandbox Code Playgroud)

有没有我忽略的复杂技术?

T.J*_*der 5

2015年更新:从下面您可以看到,甚至在2011年,Chrome和Firefox也在\n所有平台上使用。\r\nWindows上使用的Opera和IE 。从那以后,Opera像Chrome一样切换到了WebKit,因此大概使用\n。IE8是\r\n在文本区域中使用的最后一个IE 。从IE9开始,IE也使用just \n。尚未测试移动浏览器。


参加聚会的时间很晚,但是如果您真的想知道浏览器在textareas等中使用什么行分隔符(即使在同一OS上浏览器可能有所不同),则可以通过以下技巧来发现:

function getLineBreakSequence() {
    var div, ta, text;

    div = document.createElement("div");
    div.innerHTML = "<textarea>one\ntwo</textarea>";
    ta = div.firstChild;
    text = ta.value;
    return text.indexOf("\r") >= 0 ? "\r\n" : "\n";
}
Run Code Online (Sandbox Code Playgroud)

这工作,因为浏览器是使用\r\n 转换\n解析HTML字符串时,在即时。这是一个实时运行的副本,您可以使用自己喜欢的浏览器尝试一下。在IE和Opera(甚至是Opera在* nix上运行)中,您会发现它是\r\n。在Chrome,Firefox和Safari(甚至在Windows上运行)上,您会发现它是\n

就是说,我的经验是,即使在通常会使用的浏览器上,插入\n(例如,在分配给value属性时,与上面的HTML字符串相反)也能正常工作\r\n。但这并不意味着不存在极端情况,我必须承认我不textarea以任何规律性来做到这一点(在s中插入换行符),因此,如果存在问题,我确实应该\r\n在某些情况下使用浏览器,我可能只是没有找到它们。