2012-01-12 13 views
0

私はテキスト入力と隠れリストを持っています。このリストは、入力時のピント合わせやぼかしの際に表示/非表示になります。しかし、リストをクリックしたとき(入力外)にリストが表示されるようにしたい、つまりリストの外側をクリックしたときだけリストを非表示にしたい。それを達成する方法?マウスクリック時の入力ボケを防ぎます

==== ==== HTML

<input type="text" id="regioninput"> 
<ol class="continentlist"> 
    //php code to generate list items 
</ol> 

==== ==== JS

$('#regioninput').bind('focus', function() { 
    $('.continentlist').show(); 
}); 
$('#regioninput').bind('blur', function() { 
    $('.continentlist').hide(); 
}); 
$('.continentlist li').live('click', function() { 
    alert($(this).html()); 
    ... 
}); 
+0

リストにフォーカスがあるかどうかを確認することができます: 'if($('。continentlist ')。is(':focus ') 'ですが、非フォーム要素で動作するかどうかはわかりません。 .. –

答えて

3

代わりblurfocusを使用してのビットので、あなたのコードを変更することができますあなただけの異なる要素にclickを使用することができます。ここでは

//show the list when you click the input 
$('#regioninput').bind('click', function(event) { 
    event.stopPropagation(); 
    $('.continentlist').show(); 
}); 

//hide the list when the document receives a click 
$(document).bind('click', function() { 
    $('.continentlist').hide(); 
}); 

//make sure that if the user clicks on the list they won't hide it 
$('.continentlist').bind('click', function(event) { 
    event.stopPropagation(); 
}); 

はデモです:http://jsfiddle.net/qUeXS/

event.stopPropagation() DOMをバブリングからイベントを停止:サイドノートでhttp://api.jquery.com/event.stoppropagation

、これが原因でイベントバブリングの作品。ドキュメントをどこでクリックしても、documentオブジェクトは、DOMの上を泡立てた後、そのクリックイベントを受け取ります。したがって、イベントのバブリングをキャンセルすると、documentオブジェクトがイベントを受信できなくなります。

関連する問題