简体   繁体   English

使用JQuery滚动条为@ bottom时,使DIV为100%宽度

[英]make DIV 100% width when scrollbar is @ bottom with JQuery

Im trying to make a width DIV grow to 100% when the scrollbar is at the bottom, and shrink to 0% when the scrollbar is at the top of the page. 当滚动条位于底部时,我试图使宽度DIV增长到100%,当滚动条位于页面顶部时,我会缩小到0%。

I tried to make it like this : 我试着这样做:

$(document).ready(function () {



       var myWidth = $(window).width();
       var res = myWidth / 100;


       var myHeight = $(document).height();


       var myScreen = $(window).height();


       $(window).scroll(function () {

           var scrolling = $(window).scrollTop();

           var myPrecentage = (scrolling + myScreen) / (myHeight );

           console.log(myPrecentage);
           $('#com1').css("width", ((myPrecentage) * 100) + "%");



       });

   });

I came across a problem, when I try to use the scrollTop, it doesnt calculate the screen height, so I alwayes start when the scrollTop is 0, about 20% of width. 我遇到了一个问题,当我尝试使用scrollTop时,它不会计算屏幕高度,因此我总是在scrollTop为0时开始,约为宽度的20%。

have you got better idea how to tackle it ? 你有更好的想法如何解决它?

I may not have fully understood what you are trying to do, but it sounds like you want to compute % between 0 and 100% based on where you are in your scroll. 我可能还没有完全理解你想要做什么,但听起来你想根据你在滚动中的位置计算0到100%之间的%。 (Perhaps you want to translate vertical action to horizontal graph representation.) (也许您想将垂直动作转换为水平图形表示。)

Your code works, and just needs minor adjustment. 您的代码有效,只需稍作调整即可。 Right now you are computing % based on: 现在你正在计算%:

var myPrecentage = (scrolling + myScreen) / (myHeight );

What you want is: 你想要的是:

var myPrecentage = scrolling / (myHeight - myScreen);

Which is same as: 与以下相同:

$(window).scrollTop() / ($(document).height() - $(window).height());

(I should add, I'm using Chrome - behavior may differ across browsers.) (我应该补充一点,我正在使用Chrome - 浏览器的行为可能会有所不同。)

I think your current problem is that you're always starting off with the size of the view window. 我认为你当前的问题是你总是从视图窗口的大小开始。 So unless the view is at 0, you'll always start with a < zero number. 因此,除非视图为0,否则您将始终以<零数字开头。 You only want to add scrolling and myScreen when the scrolling view has passed beyond the myScreen size. 您只想在滚动视图超出myScreen大小时添加滚动和自选画面。

http://jsfiddle.net/ufomammut66/C2aFH/ http://jsfiddle.net/ufomammut66/C2aFH/

var myPrecentage;
if((scrolling - myScreen) < myScreen){
       myPrecentage = (scrolling) / (myHeight );               
} else {
       myPrecentage = (scrolling + myScreen) / (myHeight );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM