Javascript文本字段值重点
作者:互联网
环境:
请使用IE进行测试
需求:
我有一条警报消息,该消息检查用户是否输入了小于8位的值-用户将无法移至下一个字段….他应保持在同一字段上.
问题:
除了一项功能外,其他所有功能都可以正常使用-当用户在文本字段中输入小于8位的任何值时,他的焦点将以光标移至所输入值的第一个字母的方式返回,而光标应返回至输入值的最后一个字母.
码:
<html>
<body>
<script>
function checkField(field) {
if (field.value.length < 8) {
// Toggle the active element's blur off and back on after the next blur
var active = document.activeElement;
if (active && active !== field) {
var blur = active.onblur || function(){};
active.onblur = function(){ active.onblur = blur };
}
field.focus();
alert("cannot be less than 8 digits");
}
}
</script>
<input type="text" id="test1" onblur='return checkField(this);'>
<br/>
<input type="text" id="test2" onblur='return checkField(this);'>
</tr>
</table>
</body>
</html>
解决方法:
这是一种技巧,但是可以-添加一个onfocus侦听器以将其自身替换为该值,并且IE会通过将光标置于末尾来表现-onfocus =“ this.value = this.value;”:
像这样使用:
<input id="test1" type="text" value="whatever" onblur="return checkField(this);" onfocus="this.value = this.value;" />
如果您打算迁移到JQuery(建议这样做),请查看以下插件:
// jQuery plugin: PutCursorAtEnd 1.0
// http://plugins.jquery.com/project/PutCursorAtEnd
// by teedyay
//
// Puts the cursor at the end of a textbox/ textarea
// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
(function($)
{
jQuery.fn.putCursorAtEnd = function()
{
return this.each(function()
{
$(this).focus()
// If this function exists...
if (this.setSelectionRange)
{
// ... then use it
// (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
}
else
{
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
})(jQuery);
标签:onblur,focus,css,html,javascript 来源: https://codeday.me/bug/20191208/2089179.html