如何将从屏幕上滑入的输入聚焦在屏幕外?

时间:2015-03-04 06:45:45

标签: javascript html css onfocus

我有一个比#cols宽3倍的元素(<body>)。它有3列,每列都与<body>一样宽。单击按钮可将#cols元素滑动一列的宽度,同时将<input>聚焦到滑入视图的列中:

http://jsbin.com/puhurakewa/1/edit?html,css,js,output

从演示中可以看出,问题在于聚焦输入会导致奇怪的行为。我相信浏览器说,

  

Crap ,用户关注屏幕外的输入。我需要显示它!”

然后神奇地将输入滚动到视图中。这打破了过渡。

有没有办法禁用此行为?这是非常不受欢迎的。我已经在Mac上的Chrome,Safari和Firefox中注意到了它。

编辑:谢谢你到目前为止的答案。我应该对我的问题更加具体。我知道我可以通过等待动画结束来“解决”这个问题,但我很好奇的是如何通过通过这个问题并立即集中输入。这是一种更好的体验,因为用户可以在转换结束之前开始输入。

3 个答案:

答案 0 :(得分:1)

转换结束后添加焦点事件

 $('#cols').on('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', function() {
      $input.focus();
  });

JSbin Demo

答案 1 :(得分:1)

由于你已经在使用Jquery也可以利用animate方法,然后在完整的函数上集中输入,有关更多信息,请查看docs

继承人JS(这完美无缺,但如果你愿意,可以花一些时间来整理/重构):

$(document).ready(function () {
  $('button').on('click', function () {

  var colId = $('.showing').attr('id');

    if(colId == "col-1"){
      $('#cols').animate({
          right: '200px'
      }, 1000, "swing", function(){
          $("#col-2").find('input').focus();
          $('#col-1').removeClass('showing');  
          $('#col-2').addClass('showing');              
      });
    }
    else if(colId == "col-2"){
      $('#cols').animate({
          right: '400px'
      }, 1000, "swing", function(){
          $("#col-3").find('input').focus();
          $('#col-2').removeClass('showing');  
          $('#col-3').addClass('showing');                    
      });          
    }
    else if(colId == "col-3"){
      $('#cols').animate({
          right: '0px'
      }, 1000, "swing", function(){
          $("#col-1").find('input').focus();
          $('#col-3').removeClass('showing');  
          $('#col-1').addClass('showing');                    
      });          
    }
  });
});

然后将CSS更改为相对位置,如下所示:

#cols {
  height: 100%;
  transition: transform 400ms;
  white-space: nowrap;
  width: 600px;
  position:relative;
}

HTML(只需将'显示'类添加到第一个col):

<body>
   <button>Shift Cols & Focus Input</button>
   <div id="cols" col-to-show="1" >
      <div class="col showing" id="col-1">
        <input type="text" value="1" />
      </div>
      <div class="col" id="col-2">
        <input type="text" value="2" />
      </div>
      <div class="col" id="col-3">
        <input type="text" value="3" />
      </div>
  </div>
</body>

这是fiddle

答案 2 :(得分:1)

  

神奇地将输入滚动到视图

这是关键。在聚焦后,只需将容器的scrollLeft更改为0即可。我不得不在它周围放一个包装纸。

http://jsbin.com/danarucama/1/edit?html,css,js,output