使用JQuery实现鼠标悬浮时展开文本框

3

我有一个bootstrap文本输入框,我想用jquery实现以下效果:

  1. 当鼠标悬停在文本框上方时,展开文本框,并在鼠标移出时收回。 ✓ (这个jsfiddle已经完成了)

  2. 当文本框被聚焦/选中(光标位于文本框内)时,文本框会扩展,并且不会在光标悬停在外面时收回。 ✗ (需要完成)

Html

<div class="col-md-3 col-sm-3">
  <div class="input-group">
    <input class="form-control" placeholder="Search"></input>
  </div>
</div>

Javascript

$(function(){
  var form = $('.input-group');
  form.mouseenter(function(){
    form.animate({ "width": "+=" + form.width() * 1.4}, "slow");
  }).mouseout(function(){
    form.animate({ "width": '100%'}, "slow");
  });
});
5个回答

3

试试这个

$(function(){
  var form = $('.input-group');
  var start_width = form.width();

  form.find('#input-target').mouseenter(function(){
    form.animate({ "width": "+=" + start_width * 1.4}, "slow");
  }).mouseout(function(){
    form.animate({ "width": start_width+'px'}, "slow");
  }).focus(function(){
      $(this).unbind('mouseout');
      $(this).unbind('mouseenter');
  }).blur(function(){
      form.animate({ "width": start_width+'px'}, "slow");
      $(this).mouseout(function(){
        form.animate({ "width": start_width+'px'}, "slow");
      }).mouseenter(function(){
    form.animate({ "width": "+=" + start_width * 1.4}, "slow");
      });
  });
});

请看这个链接:http://jsfiddle.net/ZQ3nZ/,它与IT技术有关。

1
这非常接近我所寻找的,但有一个错误。当选中时,悬停仍然有效,使输入变得越来越长。 - Jeremy Lynch
1
哦,你可能也想解除绑定 mouseenter,否则它会一直增长,直到失去焦点。 - Sterling Archer

2

已解决 http://jsfiddle.net/mY8uU/6/

$(function(){
  var form = $('.input-group'), w = form.width();
  form.mouseenter(function(){
    form.animate({'width': '100%'}, 'slow');
  }).mouseout(function(){         
    if(!$('.form-control:focus').length) form.animate({'width': w}, 'slow');
  })
  $('.form-control').on('blur', function(){
    form.animate({'width': w}, 'slow');
  });
});

1
@Neto的解决方案也可以,但这个更加简洁,所以正确答案归于你。谢谢。 - Jeremy Lynch
谢谢!我会上传Netos的解决方案,因为他更快到达了!(您不需要console.log行) - rafaelcastrocouto

2

CSS3是不可行的吗?

如果是这样,您可以不使用Javascript并使用

.textbox{
   width: 200px;
   transition: width 1S;
}

.textbox:hover
{
    width:250px;
    transition: width 1S;
}

这只是一个例子,但您可以根据自己的喜好进行更改。


1
你可以使用一些CSS3技术来实现:
input#search {
  transition: width .5s;
  -webkit-transition: width .5s;
}
input#search:hover, input#search:focus { width:300px; }

0

这个对我有用:

$(function(){
  var form = $('.input-group');
  form.mouseenter(function(){
    form.animate({ "width":  form.width() * 1.8}, "slow");
  }).mouseout(function(){
    form.animate({ "width":  form.width() / 1.8}, "slow");
  });
});

JSFiddle: http://jsfiddle.net/mY8uU/2/


1
这在特定情况下是可行的,但如果由于某种原因宽度进一步改变,除以1.8可能不是正确的计算方法。只是提醒一下 :)(这并没有错,所以不要把这当作批评哈哈) - Sterling Archer
谢谢@RUJordan,但我希望他有足够的创造力自己完成剩下的工作 :) 只是想提供一些“工作输入” :) - Black Ops
这不是我想要的。当选择文本表单时(即插入点在文本框内部),悬停移出不应该起作用,但未选择时,悬停移出起作用。 - Jeremy Lynch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接