【问题标题】:How to focus on input with top margin如何专注于上边距的输入
【发布时间】:2012-02-28 22:23:45
【问题描述】:

我正在进行表单验证,当用户未填写必填字段之一时,我希望页面的位置专注于该输入,但我不希望输入字段直接位于浏览器框架的顶部,我希望在两者之间留一些空间,以便也可以看到输入表单的标题。

这是仅使用focus() 时的样子

但我想要这样:

这个想法是保持输入光标聚焦在输入字段上。

编辑:如果可以使用动画焦点,那就太棒了。有什么建议吗?

【问题讨论】:

  • 将输入和输入的标签包装在一个div中,关注包含输入和标签的div。
  • 看起来焦点只适用于输入,而不适用于 div

标签: jquery validation input focus margin


【解决方案1】:

使用 jQuery 的一种方法:将窗口滚动到标签的垂直偏移量。

$(function(){
    $(window).scrollTop($("label").offset().top);
    $("input").focus();
});

或者滚动到输入元素并增加一些边距:

$(function(){
    $(window).scrollTop($("input").offset().top - 100);
    $("input").focus();
});

(注意:用适当的选择器替换“输入”和“标签”)

【讨论】:

    【解决方案2】:

    让我们假设您要确保标签标签也是可见的......

    $.fn.smoothFocus = function(offset) {
       //Find the label first:
       var $labels = $(this).parent().filter("label");
    
       if ($(this).attr('id'))
           //Find labels that have a for= attributes.
           $labels.add("label[for=" + $(this).attr("id") +"]");
    
       //Find the top most label:
       var top = $(this).offset().top;
       $labels.each(function() {
           var currentTop = $(this).offset().top;
           if (currentTop < top)
              top = currentTop;
       });
    
       $(window).scrollTop(top - offset);
       $(this).focus();
    };
    
    $(".myfield").smoothFocus(10); //Sets focus to be 10px above to respective label.
    

    通过这种方式,您可以获得非常可靠的正确对焦方式。不过我没有测试。

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多