jQuery在输入表单上绑定焦点和模糊事件

问题描述 投票:1回答:3

嗨,我有一个输入表单,我也有一些标签,这些标签将帮助用户填写该表单。我的css默认设置为隐藏这些,但是当用户在输入字段上单击焦点时,将显示下一个标签,而在模糊时将隐藏该标签。

使用当前脚本,由于某种原因,我一直在显示所有标签,而且似乎并没有模糊显示它。

不是jQuery的专家,所以如果有什么可以帮助我解决这个问题,那将很好。

我的代码在下面或查看jsFiddle

js / js.js

$(document).ready(function(){
$('.form-control').bind('blur', function(){
$('.form_helper').removeClass("form_helper_show").addClass('.form_helper'); });

$('.form-control').bind('focus', function(){
$('.form_helper').removeClass("form_helper").addClass('form_helper_show'); });    

});

css / style.css

ul {
 list-style:none;
}     

li:nth-child(2), li:nth-child(3) {
display:inline;
}

.form_helper { 
display:none;   
}

.form_helper_show {
display:inline-block;   
}

index.html

<div class="form-group">
<ul class="form_group">
    <li><label for="client_name">Company Name</label></li>
    <li><input class="form-control" name="client_name" type="text" id="client_name"/></li>
    <li><label for="client_name_helper" class="form_helper">Input your clients name</label></li>
 </ul>    
</div>
 <div class="form-group">
 <ul class="form_group">
    <li><label for="client_name">Company Code</label></li>
    <li><input class="form-control" name="client_name" type="text" id="client_name"/></li>
    <li><label for="client_name_helper" class="form_helper">Input your clients code</label></li>
</ul>    
</div> 
jquery events focus blur
3个回答
12
投票

尝试

fiddle Demo

$(document).ready(function () {
    $('.form-control').bind('blur', function () {
        $(this).parent().next('li').find('.form_helper_show').removeClass("form_helper_show").addClass('form_helper');
    });

    $('.form-control').bind('focus', function () {
        $(this).parent().next('li').find('.form_helper').removeClass("form_helper").addClass('form_helper_show');
    });
});


更好的方法

fiddle Demo

$(document).ready(function () {
    $('.form-control').bind('blur', function () {
        $(this).parent().next('li').find('.form_helper').hide();
    }).bind('focus', function () {
        $(this).parent().next('li').find('.form_helper').show();
    });
});


最好使用.on()而不是.bind()

从jQuery 1.7开始,.on()方法是将事件处理程序附加到文档。对于早期版本,.bind()方法用于将事件处理程序直接附加到元素。处理程序将附加到当前选择的元素中jQuery对象,因此这些元素必须在调用时存在.bind()发生。有关更灵活的事件绑定,请参见讨论.on()或.delegate()中的事件委派。


参考文献

this keyword

.next()

.find()

.parent()


2
投票
$(document).ready(function(){
  $('.form-control').on('blur', function(e){  
      $(this).parent('li').next().find('label').removeClass("form_helper_show").addClass('form_helper'); 
  });

  $('.form-control').on('focus', function(e){
      $(this).parent('li').next().find('label').removeClass("form_helper").addClass('form_helper_show'); 
  });    

});

这应该工作


0
投票

我搜索了整个互联网,最后找到了所需的东西。

[当某物聚焦时(在我的情况下-“更多选项”按钮),我希望背景中的所有内容都像上载的图像一样模糊。

我只是通过在CSS中添加一个类来使用jQuery:

filter: blur(8px);
-webkit-filter: blur(8px);

我将此类添加到我的文章和标题中(因为我只希望它们模糊):

$('article,header')。addClass('blurItems');

现在看起来很可爱。

© www.soinside.com 2019 - 2024. All rights reserved.