【问题标题】:How to prevent the clipboard carriage return from becoming a line feed如何防止剪贴板回车变成换行
【发布时间】:2019-05-26 17:31:06
【问题描述】:

我正在为教育目的编写加密算法,并且我需要能够复制/粘贴 unicode 字符。
问题在于剪贴板(不仅是 api)将回车字符(十六进制:0x0d,十进制:13)修改为换行符(十六进制:0x0a,十进制:10)。
我怎样才能防止这种行为?

let $ = s => document.querySelector(s);

let cr = String.fromCharCode(0x0d);

$("#one").addEventListener("click", function (e)
{
	navigator.clipboard.writeText(cr);
});

$("#two").addEventListener("change", function (e)
{
	$("#out").textContent = "0x" + this.value.charCodeAt(0).toString(16).padStart(2, 0);
});
<button id="one">copy cr to clipboard</button><br>
<textarea type="text" id="two"></textarea><br>
<div id="out"></div>

您可以通过单击按钮将回车保存到剪贴板中,然后将其粘贴到文本区域中来测试它。 然后在文本区域外单击以触发更改事件。 它将显示 0x0a,因为剪贴板已将 cr 转换为 lf。

PS:我不得不从引导模式转到传统模式,因为它有问题,真的很烦人

【问题讨论】:

    标签: javascript


    【解决方案1】:

    与剪贴板无关:

    const $ = s => document.querySelector(s);
    const cr = String.fromCharCode(0x0d);
    const firstCharAsHex = v => "0x" + v.charCodeAt(0).toString(16).padStart(2, 0);
    
    $("#one").addEventListener("click", async function (e) {
      navigator.clipboard.writeText(cr);
      
      const v = await navigator.clipboard.readText();
      console.log("Written: " + firstCharAsHex(v));
    });
    
    
    $("#two").addEventListener("paste", function (e) {
      const v = e.clipboardData.getData('text/plain');
      console.log("Being paste: " + firstCharAsHex(v));
    });
    
    $("#two").addEventListener("change", function (e) {
      const v = this.value
      console.log("After paste: " + firstCharAsHex(v));
    });
    <button id="one">Run</button><br>
    <textarea type="text" id="two"></textarea><br>

    Textarea 将CR 标准化为LF。见specs

    由于历史原因,元素的值以三种不同的方式归一化,用于三种不同的目的。

    • raw value 是最初设置的值。它未标准化。
    • API value 是在value IDL 属性、textLength IDL 属性以及maxlengthminlength 内容属性中使用的值。 已标准化,因此换行符使用 U+000A LINE FEED (LF) 字符
    • 最后是value,用于本规范中的表单提交和其他处理模型。它被规范化,因此换行符使用 U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) 字符对,此外,如果必要,给定元素的 wrap 属性,插入额外的换行符以将文本换行到给定宽度。

    【讨论】:

    • 使用您的代码,我在 Firefox、Windows 上得到“写入:0x0a,粘贴:0x0a,粘贴后:0x0a”。所以如果我没记错的话,问题出在剪贴板。
    • 有趣的是,在 Firefox、Mac 上我得到了Error, Being paste: 0x0d, After paste: 0x0a,而在 Chrome 上我得到了Written: 0x0d, Being paste: 0x0d, After paste: 0x0a。两者都是最新版本
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多