最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Hiding a div on Mouse click out OR escape keyword press - Stack Overflow

programmeradmin0浏览0评论

I have the following code that hides my div (live search results) when mouse is clicked outside the div but I can't incorporate an OR function that does the same thing (hides div) when the escape key is pressed. Any help is much, much appreciated. Also, original code on mouse click out is from a different thread I got here on Stackoverflow. The or function is giving me a hard time.

var mouse_is_inside = false;

$(document).ready(function()
{
    $('.form_content').hover(function(){ 
        mouse_is_inside=true; 
    }, function(){ 
        mouse_is_inside=false; 
    });

    $("body").mouseup(function(){ 
        if $('#display').hide();
    });
});

I have the following code that hides my div (live search results) when mouse is clicked outside the div but I can't incorporate an OR function that does the same thing (hides div) when the escape key is pressed. Any help is much, much appreciated. Also, original code on mouse click out is from a different thread I got here on Stackoverflow. The or function is giving me a hard time.

var mouse_is_inside = false;

$(document).ready(function()
{
    $('.form_content').hover(function(){ 
        mouse_is_inside=true; 
    }, function(){ 
        mouse_is_inside=false; 
    });

    $("body").mouseup(function(){ 
        if $('#display').hide();
    });
});
Share Improve this question asked Jan 21, 2012 at 19:18 user1011713user1011713 2791 gold badge5 silver badges23 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

This hides #display on pressing escape:

$(document).keyup(function(event) {
    if(event.which === 27) {
        $('#display').hide();
    }
});

Example: http://jsfiddle/nsufH/

You could also try to use window instead of document:

$(window).keyup(function(event) {
    if(event.which === 27) {
        $('#display').hide();
    }
});

Or try to use live:

$(document).live('keyup', function(event){
    if(event.which === 27) {
        $('#display').hide();
    }
});

Basically you need to monitor for the KeyCode and act based off it:

$(document).keyup(function(e) {
  if (e.keyCode == 27) { $('#display').hide() }   // esc
});
$(document).ready(function() {
    $(document).on('mouseup keyup', function(e){ 
        var e = e || event,
         code = (e.keyCode ? e.keyCode : e.which),
       target = e.srcElement || e.target;

        if (target.className != 'form_content' || code==27) {
            $('#display').hide();
        }
    });
});

Here is the jsfiddle hiding a div on mouseout and ESC key press : http://jsfiddle/jrm2k6/q2kNX/

Of course there is probably some stuff to do in the way to adapt it as your own source code..

发布评论

评论列表(0)

  1. 暂无评论