2012-02-28 72 views
3

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

这是它的外观与focus()
enter image description here

但我想它是这样的:
enter image description here

的想法是让打字光标集中在输入栏。

编辑:如果可以使用动画焦点,那就太棒了。有没有建议如何做到这一点?

+0

将输入和输入的标签封装在div中,集中在包含输入和标签的div上。 – Ohgodwhy 2012-02-28 22:29:38

+0

看起来像焦点只适用于输入,而不是div – 2012-02-28 22:32:03

回答

7

使用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. 

这样你可以有非常强大的方式来获得焦点。我没有测试它。