问题描述:

internet cake for anyone who can help me with this.

I have a long (~about 3 screens long) html form, which needs to stay on one page as it's being used for data entry and going through multiple pages will slow things down.

The data entry is being done on Firefox and what I want to happen is every time the users cursor goes into/out of a field that is at or near the bottom of the visible screen, to scroll the form up more than just a single field. Each of my fields are on a new line and the default behavior with long forms in Firefox is once you hit the bottom of the screen when you tab into the next field it will scroll up the bare minimum necessary to see that field; it's frustrating for data entry as it's helpful to always be able to see ahead of what you are doing.

I don't mind using any third party js stuff (jquery/mootools etc.), I tried out the scrollTo plugin but I'm not very good with jquery so I couldn't get this to work, not even sure if it's possible.

As a side note, the behaviour I'm wanting is in Google Chrome by default, but I have to get this to work with FF unfortunately.

网友答案:

Try this (using jQuery):

$('input, textarea').on({
  focus: function (evt) {
    var
      viewportHeight = $(window).height(),
      selfBottom = $(this).offset().top + $(this).height();

    if (viewportHeight - selfBottom - $(window).scrollTop() < 10 /*minimum distance in pixel*/) {
      $(window).scrollTop(selfBottom - viewportHeight / 2);
    }
  }
});

Demo: http://jsfiddle.net/P7gd2/2/

网友答案:

I changed the focus to keyup as I don't want it autoscrolling when someone is mouse clicking on fields and I put a missing bracket around the values in the if statement, it now only scrolls when it hits the bottom of the page. (it was doing it all the time after the first time it hit the page bottom).

An 8 pixel minimum seemed to work the best for the size of my form fields and / 1.75 is a little less disorientating when the scroll happens. Code example at http://jsfiddle.net/P7gd2/6/ All credit to Yoshi for solving this.

$('input, textarea').on({
    keyup: function (evt) {
        var
        viewportHeight = $(window).height(),
        selfBottom = $(this).offset().top + $(this).height();

        if (viewportHeight - (selfBottom - $(window).scrollTop()) < 8 /*minimum distance in pixel*/) {
            $(window).scrollTop(selfBottom - viewportHeight / 1.75);
        }
    }
});
相关阅读:
Top