简体   繁体   English

单击页面上的任意位置时隐藏元素,并通过单击其他元素来显示它

[英]hide element when clicked anywhere on the page and show it by click on other element

I have an input text which i used for quick search, under this input there is a div which i use to show search result. 我有一个用于快速搜索的输入文本,在此输入下有一个div,用于显示搜索结果。 by typing in input, the result is showing up in div.now i want to hide this element (meaning div) whenever i click on window and show it again by click on the input.I tried few jquery code to hide the element but i could not show it again. 通过输入输入,结果显示在div中。现在我想在每次单击窗口时都隐藏此元素(意思是div),然后通过单击输入再次显示它。我尝试了一些jquery代码来隐藏该元素,但是我无法再次显示。

$(window).click(function () {
    $('#livesearch').hide();
});
$('#search').click(function () {
    $('#livesearch').show();
});

You should use the blur() and focus() event trigger of jQuery. 您应该使用jQuery的blur()focus()事件触发器。 doc doc

$('#input_window').blur(function () {
  $('#livesearch').hide();
}).focus(function () {
  $('#livesearch').show();
});

Change the #input_window to whatever in your html code. #input_window更改为html代码中的任何内容。

I am not sure a click event exists for the "window" object. 我不确定“窗口”对象是否存在单击事件。 But I am no expert in JS for that matter. 但是我不是JS方面的专家。

Please check this code, I think it does what you want to achieve in a bit different way. 请检查此代码,我认为它以某种不同的方式实现了您想要实现的目标。


Edit: Please check this code. 编辑:请检查此代码。 This prevents the search results from hiding if you click them. 如果您单击它们,这可以防止搜索结果隐藏。 Since I am already studying JQuery I took the time to experiment with this, achieving this functionality feels more complex than it should be :) 由于我已经在研究JQuery,因此花了一些时间对此进行试验,实现此功能比预期的要复杂得多:)

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $(':not(.search_result)').focus(function () {
            $('#livesearch').hide();
        });
        $('#search').focus(function () {
            $('#livesearch').show();
        });
    });
</script>
</head>
<body>
<div>
    <input id='search' type="text" />
    <div id='livesearch' style='display: none'>
        <ul>
            <li><a class='search_result' href='#'>result#1</a></li>
            <li><a class='search_result' href='#'>result#2</a></li>
        </ul>
    </div>
</div>
<div>
    The rest of the page.
</div>
</body>
</html>

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

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