Javascript JQuery偏移脚本
我正在为网站创建导航菜单。当用户滚动超过497px点时,需要更改颜色。我写了这个脚本:Javascript JQuery偏移脚本,javascript,jquery,Javascript,Jquery,我正在为网站创建导航菜单。当用户滚动超过497px点时,需要更改颜色。我写了这个脚本: $(document).ready(function(){ function checkOffset() { var offset = $(document).scrollTop(); console.log(offset); if(offset > 497){ $("#fixedBar").animate({backgroundCo
$(document).ready(function(){
function checkOffset() {
var offset = $(document).scrollTop();
console.log(offset);
if(offset > 497){
$("#fixedBar").animate({backgroundColor: '#1B1B1B'}, 1000);
$("#fixedBar nav a").animate({color: '#FFF'}, 1000);
}else{
$("#fixedBar").animate({backgroundColor: '#FFF'}, 1000);
$("nav a").animate({color: '#1B1B1B'}, 1000);
}
}
$(window).scroll(function() {
checkOffset();
});
});
如果我刷新页面,并且页面已经过了那个点,那么页面确实会改变,但是如果我只是滚动到那个点,页面就不会改变。如何修复此问题?您应该调用checkOffset();再来一次:
$(document).ready(function(){
function checkOffset() {
var offset = $(document).scrollTop();
console.log(offset);
if(offset > 497){
$("#fixedBar").animate({backgroundColor: '#1B1B1B'}, 1000);
$("#fixedBar nav a").animate({color: '#FFF'}, 1000);
} else {
$("#fixedBar").animate({backgroundColor: '#FFF'}, 1000);
$("nav a").animate({color: '#1B1B1B'}, 1000);
}
}
$(window).scroll(function() {
checkOffset();
});
checkOffset(); // <-- HERE
});
$(文档).ready(函数(){
函数checkOffset(){
var offset=$(document.scrollTop();
控制台日志(偏移量);
如果(偏移量>497){
$(“#fixedBar”).animate({backgroundColor:'#1B1B1B',1000);
$(#fixedBar nav a”).animate({color:'#FFF'},1000);
}否则{
$(“#fixedBar”).animate({backgroundColor:'#FFF'},1000);
$(“导航a”).animate({color:'#1B1B1B'},1000);
}
}
$(窗口)。滚动(函数(){
checkOffset();
});
checkOffset();//您的脚本可能可以工作
但因为你在每个卷轴上都有动画,所以有可能会有连续的动画循环
可能的解决方案是(上述任一点)
使用css
方法而不是animate
在设置动画之前执行stop()
,应该会有所帮助
在执行动画
方法之前,请检查现有的颜色值
要了解有关jQuery的更多信息。要使用带有颜色的.animate()
,您需要jQueryUI。因此,将框架添加到您的头部:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js""></script>
您的脚本可能可以工作。但由于您在每个卷轴上都设置了动画。有可能会有连续的动画循环。我的建议是首先暂时将animate
更改为css
方法,看看它是否工作。如果工作正常,请确保调用stop()
在制作动画之前,请参考URL,让我将此添加为答案。这对其他人也很有用。
$(function(){
$(window).on('scroll', function() {
checkOffset();
});
});
function checkOffset() {
var $target = $('#fixedBar');
var offset = $(window).scrollTop();
console.log(offset);
if(offset >= 10){
$target.stop(true, false).animate({ 'background-color': 'green'}, 1000);
//$("#fixedBar nav a").animate({color: '#FFF'}, 1000);
}
else if( offset < 10 ){
$target.stop(true, false).animate({ 'background-color': 'blue' }, 1000);
//$("nav a").animate({color: '#1B1B1B'}, 1000);
}
}