登录以使用 jquery 滚动函数将整数变量从最小值增加到最大值

Login to increase integer var from min value to max value using jquery scroll function

本文关键字:变量 最小值 增加 最大值 整数 jquery 函数 滚动 登录      更新时间:2023-09-26

我正在努力了解逻辑在parseInt内是如何工作的。

是否有人能够帮助一些逻辑(如果可能的话)来替换下面的当前-x/10

而不是从0开始,然后添加它。我试图实现30%70%之间的跨越。

$('ARTICLE A.thumb>SPAN').scroll(function(){
  var x = $(this).scrollTop();
  $(this).css('background-position','center '+parseInt(-x/10)+'%');
});

所以这个想法是当我在页面顶部时,整数将被30%,当我慢慢向下滚动页面时,这将增加,但是当我到达页面底部时,它会70%。所以最小值是30,最大值是70.

我的逻辑理解不是很好,因为我更专注于 UI,但真的很感激在这方面的一些帮助。

我已经把它变成了一个烦躁不安,但我正在尝试输出为 HTML 字符串,以便你们可以看到正在发生的事情。但是我现在什至无法获得这项工作:/

https://jsfiddle.net/w6h2z52n/3/

首先,

你的JSFiddle没有拉入jQuery - 哎呀!

此外,滚动应该发生在窗口元素上,所以我更新了 JSFiddle 以反映这一点 -

https://jsfiddle.net/w6h2z52n/7/

$(window).on('scroll', function(){
    // get our distance from top
  var x = $(this).scrollTop();
  // determine our percentage. The higher the
  // speed the slower the percentage will increment
    var speed = 30;
    var perc = x > 0 ? parseInt(x / speed) : 0;
  // now convert our percentage to between 30 and 70
  if(perc <= 30) perc = 30;
  if(perc >= 70) perc = 70;
  $('.value SPAN').html('background-position: center ' + perc + '%');
});

我添加了一个签入以确保百分比在 30 和 70 之间,尽管这可能不完全是您正在寻找的,并且某种逻辑操作将百分比转换为 30 和 70 之间的值可能会更好,但请告诉我!

编辑

这是一个不错的小挑战,所以我又试了一次,这只是一个数学案例......试一试!

https://jsfiddle.net/w6h2z52n/10/

$(window).on('scroll', function(){
    // get our distance from top
  var x = $(this).scrollTop();
  // work out our containers height
  var $container = $('.container');
    // determine percentage from top of page
  var percFromTop = ( x / $container.outerHeight() ) * 100;
  percFromTop = Math.floor(percFromTop);
  // now convert our percentage to between 30 and 70
  perc = Math.floor( 30 + (30 / 70) * percFromTop );
  $('.value SPAN').html('background-position: center ' + perc + '%');
});
呃,

这真的引起了我的兴趣,我通过以下方式解决了它

// remember last x
var lastx = 0
// the overall height
var overallheight = $(document).height()
// 70 - 30 == 50, so divide overallheight through 50 to get the "1%" in px 
var unit = (overallheight / 50)
// initial percent
var perc = 30
$(window).scroll(function(){
  var x = $(this).scrollTop();
  // if scroll down more than lastx + "1%"
  if(x >=  lastx + unit){
     // determine how many percent(step) the actual "gap" is (rounded)  
     gap = x - lastx;
     step = parseInt( gap / unit)
     // add percent
     perc += step
     lastx = x
  }
  // same reversed for scrolling back up
  if(x <=  lastx + unit){
     gap = lastx - x;
     step = parseInt( gap / unit)
     perc -= step
     lastx = x
  }
  $('.value').html('background-position: center '+parseInt(-x/10)+'%');
});

对我来说,这次尝试感觉很顺利,但由于 round(),有一些小错误,也许 Extracheck perc 不会小于 30 大于 70

https://jsfiddle.net/w6h2z52n/11/