Javascript,检测文本框是否有焦点?
我正在升级脚本以使其跨浏览器。我当前的代码如下。
function testFocus(){
var testSelection = document.getElementById('chattext').contentWindow.
window.document.selection.createRange().parentElement();
while (testSelection)
{
if (testSelection.id == "chatContent") {
return true;
}
testSelection = testSelection.parentElement;
}
return false;
}
但是,以下代码在现代浏览器中不再有效。目前,上面的代码必须选择文本。它只需要检查文本框是否具有焦点。该函数用于在通过按钮/JavaScript 添加文本之前进行检查。
I'm upgrading a script to make it crosss browser. The current code I have is as follows.
function testFocus(){
var testSelection = document.getElementById('chattext').contentWindow.
window.document.selection.createRange().parentElement();
while (testSelection)
{
if (testSelection.id == "chatContent") {
return true;
}
testSelection = testSelection.parentElement;
}
return false;
}
However the following code no longer works in modern browsers. Presently the code above has to have text selected. Where it just needs to check that the textbox has focus. The function is used as a check before text is added by a button / javascript.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让我震惊的是,您可以使用事件侦听器来设置变量。唯一的问题是 IE 使用
attachEvent(event,callback)
而不是addEventListner
,所以你实际上必须添加代码edit - 我添加了脚本标签来向您展示它如何添加到您的文档中。我已经在 Firefox 和 Chrome 中进行了测试,它似乎可以工作,但是将 IE 沙箱组合在一起对我来说可能会更困难一些。我确信我缺少一些东西 - 我会看一下。
edit2 我的 IE 代码犯了一个错误。发现你没有在
'undefined'
周围加上引号 我已经修复了上面的代码以反映在 firefox、chrome 和 IE6 中经过测试和 wotkign 的答案。我没有任何其他 IE 可以测试。Strikes me that you could use an event listener to set a variable. The only problem being that IE uses
attachEvent(event, callback)
instead ofaddEventListner
so you've actually got to add the codeedit - I've added script tags to show you how it adds to your document. I've tested in firefox and chrome and it seems to work, but getting an IE sandbox together might be a little more difficult for me. I'm sure there's something little that I'm missing there - i'll take a look.
edit2 i made a mistake with the IE code. tuns out you don't put quotes around
'undefined'
I've fixed the code above to reflect an answer that is tested and wotkign in firefox, chrome and IE6. I don't have any other IEs to test in.