使用jquery从整数中减去 [英] Subtract from an integer using jquery

查看:65
本文介绍了使用jquery从整数中减去的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望每次用户按 j 键时滚动到div。这是它的代码。

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

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

        var scroll, i,
                positions = [],
                here = $(window).scrollTop(),
                collection = $('.message_box');

        collection.each(function() {
            positions.push(parseInt($(this).offset()['top'],0));
        });

        for(i = 0; i < positions.length; i++) {
            if (direction == 'next' && positions[i] > here) { scroll = collection.get(i); break; }
            if (direction == 'prev' && i > 0 && positions[i] >= here) { scroll = collection.get(i); break; }
        }

        if (scroll) {
        $('html, body').animate({"scrollTop": $(scroll).offset().top-50});
            $(scroll).css('color', 'blue');
            $(scroll).mouseleave(function() {
            $(this).css('color', 'black');
            });
        }

        return false;
    }

    $("#next,#prev").click(function() {        
        return scroll($(this).attr('id'));        
    });
$('body').keyup(function(event) {
  if (event.which == 74) {
     return scroll('next');
   }
});
$('body').keyup(function(event) {
  if (event.which == 75) {
     return scroll('prev');
   }
});

});

我需要从div的offest中减去50来滚动到这个。

I need to subtract 50 from the offest of the div to scroll to which is this.

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

它将首次滚动,但不会滚动其余时间。我总是得到整数 218 这是要滚动到的第一个div的偏移量。
DEMO - http://jsfiddle.net/XP5sP/6/
有人可以帮助我吗?

It will scroll the first time but not the rest of the times. I always get the integer 218 which is the offset of the first div to scroll to. DEMO - http://jsfiddle.net/XP5sP/6/ Can someone help me ?

推荐答案

问题在于你总是在移动 scrollTop 在第一个匹配的元素之前,值为50像素,因此它总是将该元素标识为您需要在中滚动到的元素,如果声明,因为其位置 大于当前 scrollTop 值。

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;
}

这样可以说明窗口滚动到当前元素上方50个像素。

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

这篇关于使用jquery从整数中减去的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆