stopImmediatePropagation()的兄弟姐妹不工作

时间:2014-01-20 17:57:36

标签: javascript jquery html css

我在某些文字点击上显示搜索字段,并将其隐藏在搜索输入模糊中。

但是,如果我点击搜索按钮,我不想隐藏输入字段,并防止它被隐藏(因为模糊)。我试图stopImmediatePropagation()没有任何运气。

以下是一些代码:

// Not working. when search button is pressed, disable hiding the search input
$('.search-contacts-container > button').on('click touchstart', function(e) {
  alert('xxx');
  e.stopImmediatePropagation();
})

// when search input is blurred, hide it
$('#search-contacts').on('blur', function() {
  $('.search-contacts-container').addClass('visuallyhidden');
  $('#search-contacts').attr('required', 'false').blur();
})

// when search input is focused, show it
$('#search-contacts').on('focus', function() {
  $('.search-contacts-container').removeClass('visuallyhidden');
  $('#search-contacts').attr('required', 'true');
})

// on search text click, show the search input
$('.js-show-search').on('click touchstart', function() {
  if ($('.search-contacts-container').is('.visuallyhidden')) {
    $('.search-contacts-container').removeClass('visuallyhidden');
    $('#search-contacts').attr('required', 'true').focus();
  } else {
    $('.search-contacts-container').addClass('visuallyhidden');
    $('#search-contacts').attr('required', 'false').blur();
  }
})

HTML:

<span class="js-show-search" title="Search for contacts">Search</span>

<form action="search" method="post" class="form-search  search-contacts-container  visuallyhidden">
   <input type="text" id="search-contacts" placeholder="Search" required="false" />
   <button type="submit" class="form-search__button" title="Search"></button>
</form>

演示:http://jsfiddle.net/un775/

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

查看我的新JsFiddle。我在日常任务中使用这种方法。我希望它可以帮助你。

基本上你正在做的是添加一个背景,掩盖它背后的一切,然后添加一个点击甚至监听器来隐藏一切。表单/输入位于后台,允许您与其进行交互。

<强> HTML

<div id="js-show-search">...</div>

<form id="search-contacts" class="hide">...</form>
<div id="background" class="hide"></div>

<强>的JavaScript

var searchContact, background;

searchContact = $('#search-contacts');
background = $('#background');

$('#js-show-search').on('click', function(){
    //remove .hide to show elements
});

$('#background.close').on('click', function(){
    //add .hide to hide elements
});

<强> CSS

html, body {
    height: 100%;
}

#background {
    height: 100%;
    width: 100%;
    position: absolute;
    top:0;
    left: 0;
    z-index: 0;
}

#search-contacts {
    position: relative;
    z-index: 1;
    display: inline-block;
}

.hide {
    display: none!important;
}

http://jsfiddle.net/un775/7/