无法显示文本宽度
Unable to display width of text
当用户填写输入框时,我似乎无法使用 jquery 显示文本的宽度。我关注了Jquery documentation。也许我错过了一些我似乎看不到的东西:(
一旦通过keyup事件显示文本,宽度应该随着文本的变化而显示,对吧?有关更多信息,我一直在尝试重建这样的应用程序:Text changing application
这里是JSFiddle
<!--form begin-->
<form id="textchanger" onsubmit="return submitForm();">
<p>Preview:</p>
<!--display user input--> <span id="text-preview"><p id="prev" class="form_result"></p></span>
<p id="textCount"></p>
<!--display width-->
<p id="textWidth"></p>
<label class="sign-text">Enter your text
<input type="text" name="text" id="text" class="form-control enter-text-field validation-passed" value="Enter Your Text">
</label>
</form>
JS:
$(document).ready(function () {
$('#text').keyup(function (e, w) {
$("#prev").html($(this).val());
var txtwidth = $("#text-preview").width();
$("#textWidth").text("Approx. Width: " + txtwidth + " px.");
}).keypress(function (e) {
return /[a-z0-9.-\s]/i.test(String.fromCharCode(e.which));
});
});
在您的 $("#text-preview")
上设置 css display: inline-block;
。
跨度填满了整个宽度,因此它永远不会报告正确的大小。使用浏览器开发者工具检查宽度。
只需添加 inline-block
进行文本预览
http://jsfiddle.net/yan5L66L/2/
一些更改是有序的。 <p>
是块元素。它具有容器的宽度,而不是内部的文本。
所以
$('#text').keyup(function (e, w) {
$("#text-preview").html($(this).val());
var txtwidth = $("#text-preview").width();
$("#textWidth").text("Approx. Width: " + txtwidth + " px.");
}).keypress(function (e) {
return /[a-z0-9.-\s]/i.test(String.fromCharCode(e.which));
});
<p>Preview:</p>
<!--display user input-->
<span id="text-preview"></span>
当用户填写输入框时,我似乎无法使用 jquery 显示文本的宽度。我关注了Jquery documentation。也许我错过了一些我似乎看不到的东西:(
一旦通过keyup事件显示文本,宽度应该随着文本的变化而显示,对吧?有关更多信息,我一直在尝试重建这样的应用程序:Text changing application
这里是JSFiddle
<!--form begin-->
<form id="textchanger" onsubmit="return submitForm();">
<p>Preview:</p>
<!--display user input--> <span id="text-preview"><p id="prev" class="form_result"></p></span>
<p id="textCount"></p>
<!--display width-->
<p id="textWidth"></p>
<label class="sign-text">Enter your text
<input type="text" name="text" id="text" class="form-control enter-text-field validation-passed" value="Enter Your Text">
</label>
</form>
JS:
$(document).ready(function () {
$('#text').keyup(function (e, w) {
$("#prev").html($(this).val());
var txtwidth = $("#text-preview").width();
$("#textWidth").text("Approx. Width: " + txtwidth + " px.");
}).keypress(function (e) {
return /[a-z0-9.-\s]/i.test(String.fromCharCode(e.which));
});
});
在您的 $("#text-preview")
上设置 css display: inline-block;
。
跨度填满了整个宽度,因此它永远不会报告正确的大小。使用浏览器开发者工具检查宽度。
只需添加 inline-block
进行文本预览
http://jsfiddle.net/yan5L66L/2/
一些更改是有序的。 <p>
是块元素。它具有容器的宽度,而不是内部的文本。
所以
$('#text').keyup(function (e, w) {
$("#text-preview").html($(this).val());
var txtwidth = $("#text-preview").width();
$("#textWidth").text("Approx. Width: " + txtwidth + " px.");
}).keypress(function (e) {
return /[a-z0-9.-\s]/i.test(String.fromCharCode(e.which));
});
<p>Preview:</p>
<!--display user input-->
<span id="text-preview"></span>