【发布时间】:2020-02-14 01:46:55
【问题描述】:
目标:
我有一个输入元素,用户应该在其中输入一个介于 1 和 999 之间的数字,可以选择使用 (input type="number") 向上/向下微调器,但是当鼠标不在此元素上或元素没有焦点,我希望输入元素为“文本”类型,以确保输入的大小仅显示元素的值而不显示微调器或隐藏微调器的空白区域。这样,输入元素中的值和元素右侧的文本都不会移动,无论元素是“文本”还是“数字”类型,元素是否具有焦点,或者鼠标在元素上与否。
背景:
目前,我最初将输入元素的类型设置为“文本”,将左侧边距设置为“2ch”,将宽度设置为“4ch”,然后当鼠标悬停在元素上时,我将元素的类型设置为“ number',margin-left 到 '0',width 到 '6ch'。当鼠标离开元素或元素失去焦点时,我将这些属性设置回它们的初始值。
代码:
<style>
/* Number text (1/3 etc) */
.numbertext { color: #f2f2f2; font-size: 12px; padding: 8px 12px; position: absolute; top: -90px; }
</style>
<div class="numbertext">
<input type="text" style="text-align: right; margin-left: 2ch; width: 4ch;" min="1" max="999" value="1"
onmouseover="setInputType( 'number' );"
mouseout="setInputType( 'text' );"
onblur="setInputType( 'text' );" />/
<span>999</span>
</div>
<script>
function setInputType( type ) {
var input = window.event.currentTarget;
if( type === 'text' ) {
input.style.marginLeft = '2ch';
input.style.width = '4ch';
}
else {
input.style.marginLeft = '0';
input.style.width = '6ch';
}
input.type = type;
}
</script>
问题:
当页面最初显示时,代码以我想要的方式显示,将光标悬停在字段上或专注于它也可以。但是,在鼠标悬停在字段上之后将鼠标从字段上移开,或者字段失去焦点,会不一致地恢复输入元素的初始设置,因为 mouseout 和 blur 事件处理程序并不总是触发。我知道这一点是因为在 setInputType 函数的 if( type === 'text' ) 语句分支上设置断点并在 Chrome 检查 > 源面板中运行代码不会在鼠标移开元素后停止代码执行。
关于为什么 mouseout 和 blur 事件处理程序不能正常工作的任何想法?
解决方案:
这个CodePage 展示了一个完整的解决方案,其中包括 Bryan Elliott 的更正和 Jon P 的建议。
谢谢
【问题讨论】:
-
在您的
<input>上有mouseout="...",它必须是:onmouseout="..." -
确保也使用
focus -
是的,焦点事件也是如此,但有些不同。我在 onfocus 分配中将 hasFocused 自定义属性设置为 true,并在 onblur 分配中将此属性设置为 false。在 setInputType 函数中,我在 if( type === 'text' ) 检查之前添加了一个 if( ( typeof( input.hasFocus ) === 'undefined' ) || ( !input.hasFocus ) ) 测试,以防止输入当输入具有焦点但用户将鼠标移离元素时,属性正在更改。在 onblur 分配中,我添加了一个函数调用,该函数根据输入元素的值执行按钮的工作。
标签: javascript html events onmouseout onfocusout