在这个例子中
http://jsfiddle.net/SnJXQ/61/
读取进度指示器,但它的宽度从站点顶部增加!!
但我们需要进度条宽度开始增加
<文章内容div到文章内容结束时
这个是我们需要编辑的示例代码(HTML
<div class="bar-long"></div>
<header>Header & Menu
<br>header and menu content
<p>Header & Menu
<br>header and menu content
<p>Header & Menu
<br>header and menu content
<p>
</header>
<h1>Begin Article <br>(Need show Bar from here) </h1>
<p>
<article>
<div class="bar-long2">article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />article content
<br />
</div>
<div class="bar-long3">
<h1>EndEndEnd<br> (Need width Bar 100%</h1>
</div>
</article>
<footer>
<h1>Footer</h1>
<div class="footer">
<h4>Footer</h4>
<h4>Footer</h4>
<h4>Footer</h4>
<h4>Footer</h4>
<h4>Footer</h4>
</div>
</footer>
CSS
.bar-long {
height: 5px;
background-color: #009ACF;
width: 0px;
z-index: 1000;
position: fixed;
top: 50px;
left: 0;
}
body {
height:2000px;
}
Jquery的
$(window).scroll(function () {
// calculate the percentage the user has scrolled down the page
var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $('article').height());
$('.bar-long').css('width', scrollPercent + "%");
});
答案 0 :(得分:5)
它有点复杂,但最后
$(window).scroll(function() {
// calculate the percentage the user has scrolled down the page
var scrollwin = $(window).scrollTop();
var articleheight = $('article').outerHeight(true);
var windowWidth = $(window).width();
if(scrollwin >= $('article').offset().top){
if(scrollwin <= ($('article').offset().top + articleheight)){
$('.bar-long').css('width', ((scrollwin - $('article').offset().top) / articleheight) * 100 + "%" );
}else{
$('.bar-long').css('width',"100%");
}
}else{
$('.bar-long').css('width',"0px");
}
});
让我解释一下这里发生了什么
宽度百分比将来自文章中传递scrollTop的部分并除以文章高度以获得该部分的百分比
在if语句中我创建第二个if语句,以便在每次向下滚动文章时将蓝色栏停止在100%不增加
所以无论你的文章高度如何,这段代码都可以使用
答案 1 :(得分:0)
你的计算方法错误,这是正确的:
var scrollPercent = 100 * ($(window).scrollTop() - $('article').offset().top) / $('article').height();
FIDDLE:https://jsfiddle.net/SnJXQ/62/
注意:我将background-color
设置为article
以更好地查看计算结果。