2010-08-02 66 views
2

我有following code的JavaScript模糊點擊不合羣

HTML:

<input type='text' class='a' /> 
<div class='inst' tag='a'></div> 
<input type='text' class='b' /> 
<div class='inst' tag='b'></div> 
<input type='text' class='c' /> 
<div class='inst' tag='c'></div> 

JS:

$(function() { 
    $('.inst').click(function() { 
     alert($(this).attr('tag') + ' clicked'); 
    }); 

    $('[type=text]').focus(function() { 
     show_inst($(this).attr('class')); 
    }).blur(function() { 
     //hide_inst($(this).attr('class')); 
    }); 

    function show_inst(tag) { 
     $('div.inst[tag=' + tag + ']').html(tag + ' instructions'); 
    } 

    function hide_inst(tag) { 
     $('div.inst[tag=' + tag + ']').html(''); 
    } 
}); 

CSS:

.inst { 
    width: 200px; 
    height: 100px; 
    border: 1px solid black; 
    margin: 10px; 
    cursor: pointer; 
} 

它正常工作:當時點擊我看到了提示信息,當輸入變爲焦點時,指令出現。

現在我想讓不相關的指令在模糊時消失。所以我試圖在blur()內添加註釋行。它不起作用,因爲blur()被首先調用並刪除指令,所以如果我點擊指令 - 什麼都不會發生。

我該如何解決這個問題?

+0

因此,指令需要留在div當你點擊它,當你點擊任何其他指令需要消失? – Fabian 2010-08-02 07:10:12

+0

是的。什麼是實施這個最好的方法? – 2010-08-02 07:29:20

回答

3

如果您唯一的問題是該指令在點擊它之前被隱藏,請考慮添加一個小小的延遲。這將基本上導致您的隱藏指令在點擊處理後執行。

事情是這樣的:

$('[type=text]').focus(function() { 
    show_inst($(this).attr('class')); 
}).blur(function() { 
    setTimeout(function(){ 
    hide_inst($(this).attr('class')); 
    }, 50); // make this happen after any other events 
}); 
1
 var timeoutId; 
     $('[type=text]').on("blur", function(){ 
      timeoutId = setTimeout(function(){      
       console.log("blur"); 
      }, 50); 
     }).on("focus", function(){ 
      clearTimeout(timeoutId); 
     }); 

或者你可以試試這個,它只會當你離開輸入(「假」點擊通過clearTimeout刪除)消防模糊。