【问题标题】:Javascript change target element of keydown / keypress eventJavascript更改keydown / keypress事件的目标元素
【发布时间】:2016-12-07 06:22:01
【问题描述】:

我有一个 div,它接收一个 keydown 事件,一旦触发,我想将焦点更改为一个输入字段,以便用户输入文本。输入字段在 keydown 之前是隐藏的。

我想以某种方式阻止默认的 keydown 事件,将事件目标更改为输入元素,然后再次触发它,将键入的值插入到输入中。

有没有办法在触发之前更改 keydown 事件元素?


另一种方法是解释初始击键并将其作为输入元素的值输入,然后专注于剩余的输入。这有点混乱,但可能是必要的。


https://jsfiddle.net/fr5xrsyd/4/

$('.focus').keydown(function(e){
	$('input').addClass('keydown');
  e.preventDefault();
  e.target = $('input')[0];
  //fire event after target changed
});
.container {
  position: relative;
}

.focus {
  border: 2px solid blue;
  text-align: center;
  padding: 0.5em;
  z-index:1
}

.focus:focus {
  border: 2px solid red;
}

input {
  width: 100%;
  height: 100%;
  z-index: 2;
  position: absolute;
  top: 0;
  left: 0;
  text-align: center;
  display: none;
}

input.keydown {
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="focus" tabIndex="-1">
    Click me and type a value.
  </div>
  <input placeholder="typed value should appear here"/>
</div>

【问题讨论】:

  • “有没有办法在触发之前更改 keydown 事件元素?” - 您说您正在尝试这样做以响应您想要的相同 keydown 事件改变,所以那个时候事件已经发生了。顺便说一句,您为什么要让仅使用键盘的用户无法使用您的页面?
  • 所以唯一的方法是解释初始击键,并将其作为输入元素的值输入,然后将输入聚焦于剩余的击键?
  • @RyanKing 试试$('input').focus()
  • 成功了!

标签: javascript keyboard-events


【解决方案1】:

$('input').focus() 按照上面 prasad 的评论做到了这一点。

$('.focus').keydown(function(e){
	$('input').addClass('keydown');
  $('input').focus();
});
.container {
  position: relative;
}

.focus {
  border: 2px solid blue;
  text-align: center;
  padding: 0.5em;
  z-index:1
}

.focus:focus {
  border: 2px solid red;
}

input {
  width: 100%;
  height: 100%;
  z-index: 2;
  position: absolute;
  top: 0;
  left: 0;
  text-align: center;
  display: none;
}

input.keydown {
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="focus" tabIndex="-1">
    Click me and type a value.
  </div>
  <input placeholder="typed value should appear here"/>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多