这个计算页面滚动的非常简单的函数在jsfiddle上运行得很好,但我无法在我的页面上运行它。
因此功能如下: -
jQuery(document).ready(function($) {
$(window).scroll(function() {
var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
$('.bar-long').css('width', scrollPercent +"%" );
});
});
简单,对吧?事实上,它从来没有将css应用于我当地环境中的长条级div,只是很奇怪。
所以我认为它可能是窗口滚动功能的问题,所以我这样做了: -
jQuery(document).ready(function($) {
// Inside of this function, $() will work as an alias for jQuery()
// and other libraries also using $ will not be accessible under this shortcut
$(window).scroll(function() {
var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
$('.bar-long').css('width', scrollPercent +"%" );
});
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 100) {
$("body").addClass("scrolled");
} else {
$("body").removeClass("scrolled");
}
});
});
第二个功能测试我没有做出一个完全愚蠢的错误,我不是,第二个功能工作正常。
我正在使用捆绑版本的jQuery1.11.1运行WordPress,因此是noconflict jQuery限定符。
我甚至将我的整个css粘贴到jsfiddle以及我的网站html的副本/面食,工作得很好。
我已禁用网站上的其他脚本,与这些脚本没有冲突,控制台没有错误。
只是困惑,真的很困惑。编辑: - 在一些控制台记录之后;
console.log($(window).height());
console.log($(document).height());
console.log ($(document).height() - $(window).height());
=
5541
5541
0
因此它认为窗口高度和文档高度是相同的,它们不是。 HRMM。
答案 0 :(得分:1)
我解决了。
全能的神圣基督,这是因为chrome与doctypes相混淆并且认为窗口/文档高度是相同的,如果你搞砸了,我使用这个:
<!DOCTYPE html <?php language_attributes(); ?>>
,我从它移除了PHP,现在它工作得很好。
感谢所有帮助过的人。一个好的FYI,doctypes很重要。
答案 1 :(得分:0)
根据您的评论,听起来您的代码试图除以零。
如果$(document).height() - $(window).height()
是0
,那么您正在执行100 * $(window).scrollTop() / 0
,根据我的firefox控制台显示为Infinity
。
您无法在元素上设置width: Infinity%;
,因此请先检查!像这样:
// Avoid a divide by zero error
var docHeight = $(document).height() - $(window).height();
if (docHeight < 1) {
docHeight = $(document).height();
}
var scrollPercent = 100 * $(window).scrollTop() / docHeight);
答案 2 :(得分:-1)
尝试更改类或增强选择器$('.parent-div .bar-long')
等的特异性
此外,检查开发工具(Chrome检查器,Firebug等)中的计算样式,以查看正在应用或覆盖级联中的哪些样式。