Unicode <input />值在浏览器之间显示不同

时间:2016-05-21 15:47:41

标签: javascript jquery html unicode

我正在使用jQuery将文本输入的值设置为一串unicode字符(它使用vanilla js重新编写):

$(function() {  
    var value = "\u0000J\u0000o\u0000a\u0000n\u0000 \u0000J\u0000e\u0000t\u0000t\u0000 \u0000a\u0000n\u0000d\u0000 \u0000T\u0000h\u0000e\u0000 \u0000B\u0000l\u0000a\u0000c\u0000k\u0000h\u0000e\u0000a\u0000r\u0000t\u0000s\u0000";

    var $input = $('<input type="text" style="width: 200px;"></input>').val(value);

    $('body').html($input);
});
<html>
    <head>
        <meta charset="utf-8" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    <body>
    </body>
</html>

我已经针对Chrome,Firefox和Safari的最新版本进行了测试,并且这三种行为都有所不同,Chrome的表现最为出色:

Chrome 50.0:

Chrome

Safari 9.1.1:

Safari

Firefox 46.0

Firefox

1 个答案:

答案 0 :(得分:0)

您可以<pre>元素设置contentEditable属性,css appearance设置为textfield:focus来应用<input> :focus元素focus上的元素<pre>样式

var value = "\u0000J\u0000o\u0000a\u0000n\u0000 \u0000J\u0000e\u0000t\u0000t\u0000 \u0000a\u0000n\u0000d\u0000 \u0000T\u0000h\u0000e\u0000 \u0000B\u0000l\u0000a\u0000c\u0000k\u0000h\u0000e\u0000a\u0000r\u0000t\u0000s\u0000";
var text = $("<pre>", {
  text: value,
  contentEditable: true,
  class:"input"
});
$("body").append(text);
pre.input {
  -webkit-appearance: textfield;
  -moz-appearance: textfield;
  background-color: white;
  border-image-source: initial;
  border-image-slice: initial;
  border-image-width: initial;
  border-image-outset: initial;
  border-image-repeat: initial;
  -webkit-rtl-ordering: logical;
  -webkit-user-select: text;
  cursor: auto;
  padding: 2px;
  border-width: 1px;
  border-style: solid;
  border-color: #A8A8A8;
  border-radius: 2px;
  width: 200px;
  overflow-x:hidden;
  font-family:arial;
  font-size:13.3333px;
}
pre.input:focus {
  outline: -webkit-focus-ring-color auto 5px;
  outline-style: none;
  border-color:dodgerblue;
  border-width:2px;
  box-sizing:content-box;
  box-shadow:.025em .025em .025em dodgerblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="text" value="Joan Jett and The Blackhearts" />
<!-- compare appended `<pre>` element -->