Set div width based on scroll position

时间:2015-08-06 13:54:27

标签: javascript html css scrollbars

The code: http://codepen.io/anon/pen/EjrpMM

So, i'm working on an interesting problem. I am working with a 2000px HTML document, that has a modal placed ontop of it.

The width of the div lightbox is 80%, and it's sitting positioned fixed.

The goal is, when scrolling down the page, to control the width of the div based on the scroll position. At the bottom of the page, it's only a third in size.

I've had trouble figuring out the proper equation or formula for this, and was seeking help.

Currently, I've been trying to look at the window.pageYOffset, to add 2.5% to the div while increasing, and minus 2.5% when scrolling back up, to bring it back to it's 80% width.

However, something isn't working right. I was seeing if the community had any ideas to help solve the problem.

I'm not using any frameworks for this.

Here's my javascript:

var lightBox = document.getElementById('lightBox'),
count = 80,
num = window.pageYOffset;

document.addEventListener('scroll', function(e) {
  var offset = window.pageYOffset;

  num >= offset ? count += 2.5 : count -= 2.5;
  num = offset;

  lightBox.style.width = count + '%';
});

View the code here, in this codepen

http://codepen.io/anon/pen/EjrpMM

Thank you!

3 个答案:

答案 0 :(得分:0)

你只需要改变

        for (int i = 0; i < layoutManager.getChildCount(); i++) {
            LinearLayout container = (LinearLayout)layoutManager.getChildAt(i);
            LinearLayout container2 = (LinearLayout)container.getChildAt(0);
            Object tag = container2.getTag();
        }

当我检查你的代码时,我做了这个并且它有效。

答案 1 :(得分:0)

滚动事件在滚动时单独滚动一次,滚动了多少。例如。如果您已滚动1px滚动条,或使用鼠标滚动滚动100px滚动事件将被触发一次。

因此,如果您需要稳定的结果,则需要根据滚动位置(window.pageYOffset)计算div宽度。

检查codepen fork。我假设在页面末尾div宽度应为50%

核心部分是:

var lightBox = document.getElementById('lightBox');
var upperBound = 80;
var lowerBound = 50;

var tickValue = (upperBound - lowerBound) / window.innerHeight;

document.addEventListener('scroll', function(e) {
  var offset = window.pageYOffset;
  var count = upperBound - offset * tickValue;

  lightBox.style.width = count + '%';
});

重要说明:对于获取innerHeight的crossbrowser方式,您可以查看this answer

答案 2 :(得分:0)

这是一个简单的等式。让f : scroll |-> f(scroll)成为赋予div宽度的函数。你想要f(0) = 0.8, f(2000)= 1/3

假设您希望渐进线性为f(scroll) = a*scroll + b,您可以轻松推断出b = 0.8a = (1/3 - 0.8)/2000 = -0.000233。现在,对于任何滚动值,您都可以找到div的宽度。

现在,您可以根据需要更改值f(scroll) = (minWidth-maxWidth)/pageLength * scroll + maxWidth