Subtract from an integer using jquery

后端 未结 3 1350
北恋
北恋 2021-01-27 06:20

I want to scroll to a div each time user presses j key. Here is the code for it.

$(function() {
    function scroll(direction) {

        var s         


        
相关标签:
3条回答
  • 2021-01-27 07:15

    $(scroll).offset().top-50 is prefectly valid, as .top will return an integer value. Therefore the issue is not with this portion of your code.

    I suspect the issue is to do with the scroll variable you have within the scroll function. I always keep away from naming my variables the same as my function names when within the same scope.

    0 讨论(0)
  • 2021-01-27 07:16

    The problem is that you're always moving the scrollTop value to 50 pixels before the first matched element, so it's always identifying that element as the one you need to scroll to in your if statement because its position is greater than the current scrollTop value.

    Modify the relevant section of your code to this:

    if (direction == 'next' && positions[i] > here + 50) {
        scroll = collection.get(i);
        break;
    }
    

    That way it accounts for the window being scrolled to 50 pixels above the current element.

    0 讨论(0)
  • 2021-01-27 07:18

    Try putting some space between your minus symbol so it does not get mistaken for a dash.

    $('html, body').animate({"scrollTop": $(scroll).offset().top - 50});
    

    or save your mathematics in a variable first

    var scrollMinusFifty = $(scroll).offset().top - 50;
    $('html, body').animate({"scrollTop":scrollMinusFifty});
    
    0 讨论(0)
提交回复
热议问题