Da *_*nan 10 html javascript jquery event-propagation dom-events
我想将可编辑div中的字符数限制为10.在用户达到限制后,我想使用.preventDefault()方法来保护div免受其他字符的影响.你能救我吗?JSFiddle https://jsfiddle.net/7x2dfgx6/1/ HTML
<div class="profileInfo" id="About" style="border:solid;" contenteditable="true">OOOOO</div>
Run Code Online (Sandbox Code Playgroud)
JQuery的
jQuery(document).ready(function($){
const limit = 10;
rem = limit - $('#About').text().length;
$("#counter").append("You have <strong>" + rem + "</strong> chars left.");
$("#About").on('input', function(event) {
var char = $('#About').text().length;
rem = limit - char;
$("#counter").html("You have <strong>" + rem + "</strong> chars left.");
if(char>limit)
{
event.preventDefault();
//TODO
}
});
});
Run Code Online (Sandbox Code Playgroud)
Art*_*iak 17
要回答你的主要问题:
.preventDefault()
取消是事件的行为取消.input
事件不是.
要检查是否event
可取消,请尝试:console.log(event.cancelable);
.
因为input
它会说"假"
你可能想要这样的东西(未经测试):
const limit = 10;
var rem = limit - $('#About').text().length;
$("#counter").append("You have <strong>" + rem + "</strong> chars left.");
$("#About").on('input', function(event) {
var char = $(this).text().length;
rem = limit - char;
if(rem <= 0){
$(this).text($(this).text().slice(0, limit));
}
$("#counter").html("You have <strong>" + rem + "</strong> chars left.");
});
Run Code Online (Sandbox Code Playgroud)
编辑
JSFiddle演示
由于它是contentEditable,我不得不使用额外的代码(来自这个答案)在输入的末尾设置一个插入符号.
使用keydown
代替input
jQuery(document).ready(function($){
const limit = 10;
rem = limit - $('#About').text().length;
$("#counter").append("You have <strong>" + rem + "</strong> chars left.");
$("#About").on('keypress', function(event) {
var char = $('#About').text().length;
if(char>limit)
{
return false;
//or
event.preventDefault();
//TODO
}
rem = limit - char;
$("#counter").html("You have <strong>" + rem + "</strong> chars left.");
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14596 次 |
最近记录: |