显示/隐藏" div" JS;

时间:2015-02-09 13:53:02

标签: javascript jquery html css

我试图用简单的JS效果进行搜索,但我被困在一个地方。 当我点击.search时,显示.s_holder的div,然后再点击它隐藏。问题是,当我点击input字段或div s_holder - div时,表单会隐藏。

<div class="search">
        <div class="s_holder">
            <form name="search" method="post" action="../test.php">
                <input type="search" name="query" placeholder="search">
            </form>
        </div>
    </div>

<script>
var a=true;
    $('.search').bind('click',function(){
        if (a==true){
        $('.s_holder').show();
            a=!a;
        }else{
            $('.s_holder').hide();
            a=!a;
        }
    });
</script>

<style>
    .search {
        background-image: url("../images/writers/search.png");
        background-repeat: no-repeat;
        float: left;
        height: 52px;
        width: 52px;
        margin-right: 2%;
    }
    .s_holder{
        display: none;
        width: 300px;
        float: left;
        background-color: rgba(17, 17, 17, 0.12);
        height: 52px;
        border-radius: 25px;
    }
    .search input[type=search]{
        margin-left: 65px;
        margin-top: 15px;
        width: 205px;
    }
</style>

2 个答案:

答案 0 :(得分:4)

您需要检查e.target属性,以查看该事件是否已从子元素冒泡。如果有,您可以停止执行:

var a = true;
$('.search').bind('click', function (e) {
    if (e.target != e.currentTarget) // the click bubbled 
        return;

    if (a == true) {
        $('.s_holder').show();
        a = !a;
    } else {
        $('.s_holder').hide();
        a = !a;
    }
});

Example fiddle

答案 1 :(得分:0)

问题不像它看起来那么简单。 当您显示div的内容时,表单和div.s_holder会覆盖它,拦截点击并阻止单击原始元素。 您需要将点击应用于除输入字段以外的所有元素:

(另外,这里有一个更简单的代码,没有笨拙的if(a==true)

$('.search, .s_holder, form').click(function(e){
    if(e.target != this) return;
    $('.s_holder').toggle();
});
.search {
    background-image: url("../images/writers/search.png");
    background-repeat: no-repeat;
    float: left;
    height: 52px;
    width: 52px;
    margin-right: 2%;
    border: blue solid 1px;
}
.s_holder{
    display: none;
    width: 300px;
    float: left;
    background-color: rgba(17, 17, 17, 0.12);
    height: 52px;
    border-radius: 25px;
}
.search input[type=search]{
    margin-left: 65px;
    margin-top: 15px;
    width: 205px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search">
        <div class="s_holder">
            <form name="search" method="post" action="../test.php">
                <input type="search" name="query" placeholder="search">
            </form>
        </div>
    </div>

http://jsfiddle.net/9zgg3o75/2/