当用户在文本框中时阻止javascript keyup功能效果?

时间:2014-04-25 17:44:22

标签: javascript jquery keyup onkeyup

目前我使用以下代码允许用户“翻转”#34;我的网络应用上的内容:

$(this).keyup(function(e) {
    if(e.which == 37) {
        document.location = $("#prev_button").attr('href');
    }else if(e.which == 39) {
      document.location = $("#next_button").attr('href');
    }
});

问题在于,如果用户位于页面顶部的搜索表单中,我不希望箭头键重定向页面(相反,它们应该像通常那样没有功能,即允许文本光标移动文本)。

表单ID是" searchForm" - 我可以在if语句中添加一个子句,如果选择了搜索表单,则该子句的计算结果为false吗?

3 个答案:

答案 0 :(得分:3)

您可以在文本框中停止事件的传播,以便事件不会传递给您的其他处理程序:

$('#searchbox').keyup(function(e) {
    e.stopPropagation();
});

答案 1 :(得分:1)

我会使用类似:Demo

的内容
$(this).keyup(function(e) {
    if(~['input', 'textarea'].indexOf(e.target.tagName.toLowerCase())) return;
    if(e.which == 37) {
        document.location = $("#prev_button").attr('href');
    }else if(e.which == 39) {
        document.location = $("#next_button").attr('href');
    }
});

这样您就可以排除所有<input><textarea>元素。

IMO(仅#searchbox除外)不是一个很好的解决方案,因为将来您可以更改其id或包含其他文本字段,但忘记您必须反映排除脚本中的更改。< / p>

答案 2 :(得分:1)

看看这个帖子:) Find if a textbox is currently selected

function checkFocus() {

  if ($(document.activeElement).attr("type") == "text" || $(document.activeElement).attr("type") == "textarea") {

  //Something's selected

  return true;

 }

}