繁体   English   中英

在html中的两个单词之间插入空格

[英]Insert blank space between two words in html

我想在两个词之间插入一些空格,我不想使用pre标签。 在我的代码中,这是一个输入字段,用户可以在其中输入文本,一些 javascript 代码将其显示在div您可以查看下面的代码。

<input type="text" id="user-input" />

<div id="user-text"></div>

Javascript代码

    $(document).on('keyup', '#user-input', function(event){
var userText = $('#user-text');
var clientText = $(this).val().toUpperCase();
if(event.keyCode === 32 || event.which === 32){ clientText += '&nbsp;';  }
    clientText = $('<textarea />').html(clientText).text();

    userText.text(clientText);
});

我正在使用&nbsp; 用于在两个单词之间插入空格,但这不起作用。 如果我想插入十个空格,它只插入一个空格然后什么。 该代码无法正常工作,因为我预计您无法使用此代码插入多个空格。

更新
我想要这样。

在此处输入图片说明

可以插入多个&nbsp; 文本,它将正确显示。 简单的空格被截断为单个。

 $(document).ready(function () { $('input').on('input change', function () { $('#span1').html( $(this).val() + '&nbsp;'.repeat($(this).val().length) ); $('#span2').html( $(this).val() + ' '.repeat($(this).val().length) ); }); })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" placeholder="Some text"/><br/> <span id='span1'>Some text</span>Other text to pad with <b>&amp;nbsp;</b>.<br/> <span id='span2'>Some text</span>Other text to pad with <b>white-space</b>.


要保留用户输入的空格:

 $(document).ready(function() { $('input').on('input change', function() { $('span').html( $(this).val().toUpperCase().replace(/\\s/g, '&nbsp;') ); }) })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='text' /> <br/> <span></span>

如果你真的想插入说 10 个空格,那么你必须把 &nbsp 10 次

clientText += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';

您可以在此处了解有关与空格相关的 HTML 实体的更多信息。

您可以使用 replace() 将所有 \\s 等效空间替换为 nbsp;

var userText = $('#user-text');
$(document).on('input', '#user-input', function(event){
    userText.html( $(this).val().replace(/\s/g,'&nbsp;') );
});

演示

我创建了一个简单的 convertSpace 函数来处理将空格转换为 nbsp。 https://jsfiddle.net/elemilion/6own3g7z/

function convertSpacesToNbsp(str){
return str.split('').map(function(char){
if(char === ' '){
    char = '&nbsp;';
}
return char;
}).join('');
}
$(document).on('keyup', '#user-input', function(event){
var userText = $('#user-text');
var inputStr = $(this).val().toUpperCase();
var clientText = convertSpacesToNbsp(inputStr);
userText.html(clientText);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM