简体   繁体   English

更改布局的Javascript / jQuery focusout事件会导致click事件无法触发

[英]Javascript/jQuery focusout event that changes layout causes click event to not fire

I have a field that when you leave focus on it, it changes the layout of the page. 我有一个字段,当你把焦点放在它上面时,它会改变页面的布局。 I also have buttons on the page that submit my form. 我还在页面上有提交表单的按钮。

If I go into my field and type a value, then click the button, the button click event never fires. 如果我进入我的字段并键入值,然后单击按钮,按钮单击事件永远不会触发。 This seems to happen because the layout is changing before the click event gets fired, which means the button changes places. 这似乎是因为布局在click事件被触发之前发生了变化,这意味着按钮会改变位置。 By the time the click event fires, it's firing on an empty area, not the button. 当click事件触发时,它会在空白区域而不是按钮上触发。

Here is a jsfiddle of the issue: http://jsfiddle.net/xM88p/ 这是问题的一个方面: http//jsfiddle.net/xM88p/

I figured out a way to solve this for IE but after extensive research I can't find/access the same object in FF/Chrome: 我找到了一种解决这个问题的方法,但经过大量研究后,我无法在FF / Chrome中找到/访问同一个对象:

//only works in IE

if(event.originalEvent.toElement){
  $("#"+event.originalEvent.toElement.id).click();
}

http://jsfiddle.net/xM88p/2/ http://jsfiddle.net/xM88p/2/

Use mousedown instead of click : 使用mousedown而不是click

$("#btn_test").on('mousedown', function (event){
    alert("clicked!"); 
});

$('#test').focusout(function (event){
    $('<p>Test</p>').insertAfter(this);
});

Edit 编辑

Okay, I got a little more creative with the event handlers. 好的,我对事件处理程序更有创意。 The new solution keeps track of mousedown/mouseup events as well as the position of the click. 新解决方案会跟踪mousedown / mouseup事件以及点击的位置。 It uses these values to check whether mouse up should execute an alert. 它使用这些值来检查鼠标是否应该执行警报。

var testClicked = false;
var lastX, lastY;

$(document).on('mouseup', function (event) {
    if (testClicked === true && lastX === event.clientX && lastY === event.clientY) {
        alert("clicked!"); 
    }
    testClicked = false;
    lastX = null;
    lastY = null;
});

$("#btn_test").on('mousedown', function (event){
    testClicked = true;
    lastX = event.clientX;
    lastY = event.clientY;
});

$('#test').focusout(function (event){
    $('<p>Test</p>').insertAfter(this);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM