我正在尝试将点击事件从屏幕上的某个元素重定向到屏幕外的文本输入。单击屏幕上的元素会触发在屏幕外元素上模拟相同事件的处理程序。
当用户通过浏览器单击文本输入时,文本输入的焦点和单击处理程序都会触发。但是,当在屏幕外文本输入上调度模拟的单击事件时,不会发生焦点事件。
此外,当在文本输入上触发模拟焦点事件时,光标不会出现在文本输入中,就像单击了文本输入一样。
http://jsfiddle.net/k32n30vf/2/提供了可运行的代码段,因为SO不支持CoffeeScript。
代码(CoffeeScript)
one = document.getElementById("one")
two = document.getElementById("two")
logger = document.getElementById("log")
#In order for the span to be focusable, it must have tabIndex != -1
one.tabIndex = 0
#Adds text to top of logger paragraph
log = (message) ->
entry = document.createElement('p')
entry.classList.add("log")
entry.innerText = message
logger.insertBefore(entry, logger.firstChild)
#Event listener that logs events w / source
reportEvent = (event) -> log("#{event.currentTarget.id} #{event.type}")
#Listen on click and focus for both elements
e.addEventListener "click", reportEvent, false for e in [one, two]
e.addEventListener "focus", reportEvent, false for e in [one, two]
#Generic simulate method
simulate = (what, where) ->
where = if where == "one" then one else two
what = if what == "click" then new MouseEvent("click") else new FocusEvent("focus")
where.dispatchEvent what
#Wire up buttons
document.getElementById("sim-one-clk").addEventListener("click", () -> simulate("click", "one"))
document.getElementById("sim-two-clk").addEventListener("click", () -> simulate("click", "two"))
document.getElementById("sim-one-fcs").addEventListener("focus", () -> simulate("focus", "one"))
document.getElementById("sim-two-fcs").addEventListener("focus", () -> simulate("focus", "two"))
CSS
p.log {
margin: 0px;
padding: 0px;
}
HTML
<p> Instructions:</p>
<ol>
<li> Click "Simulate Click on #2"</li>
<li> Note how no text cursor appears on input</li>
<li> Actually click on input</li>
<li> Note how text cursor appears on input</li>
</ol>
<p><span id="one">This span is #1</span>
</p>
<p>
<input id="two" value="this input is #2"></input>
</p>
<p>
<input id="sim-one-clk" type="button" value="Simulate Click on #1"></input>
</p>
<p>
<input id="sim-one-fcs" type="button" value="Simulate Focus on #1"></input>
</p>
<p>
<input id="sim-two-clk" type="button" value="Simulate Click on #2"></input>
</p>
<p>
<input id="sim-two-fcs" type="button" value="Simulate Focus on #2"></input>
</p>
<p id="log"></p>
请注意,如果屏幕上的元素被聚焦并且按下了 Simulate Click on#2 按钮,则文本光标不会出现在屏幕外元素中。但是,单击屏幕外元素会导致文本光标出现。