我有一个使用 d3.js 制作的图表:
我已将此图表放在网站中。
问题是在上面的网站中,当你滚动页面到“teamchart”部分时,我没有看到图表的效果。当您刷新页面时,您可以看到图表作用的效果。
我想让图表发挥作用并显示效果,当我到达页面的该部分或当我使用导航栏时,单击“teamchart”并到达该部分。
我使用了下面的 JavaScript 代码,但它不断重复:
$(document).scroll(function() {
//Basically your position in the page
var x = $(this).scrollTop();
//How far down (in pixels) you want the user to be when the effect to starts, eg. 500
var y = 500;
if (x > y) {
//Put your effect functions in here.
}
});
与网站相关的 fiddle :
My code related to website (在这里做实验)
最佳答案
据我了解,您的问题是动画持续播放的部分。
这是因为每次您将页面滚动到大于 500 的值时,您实际上是在重复您的代码。
简单的解决方案:放置一个标志来表示'alreadyAnimated'
var g_pieChartAnimated=false;
$(document).scroll(function() {
//Basically your position in the page
var x = $(this).scrollTop();
//How far down (in pixels) you want the user to be when the effect to starts, eg. 500
var y = 500;
if (!g_pieChartAnimated && (x > y)) {
g_pieChartAnimated = true;
//Put your effect functions in here.
}
});
第二种解决方案(快一点):
是在事件处理程序完成您想要的操作后将其分离。
function onScroll_AnimateChart() {
//Basically your position in the page
var x = $(this).scrollTop();
//How far down (in pixels) you want the user to be when the effect to starts, eg. 500
var y = 500;
if (!g_pieChartAnimated && (x > y)) {
$(document).off('scroll', onScroll_AnimateChart); // remove myself from the event handlers, so it won't be called again.
//Put your effect functions in here.
}
}
$(document).on('scroll', onScroll_AnimateChart);
关于javascript - 仅当在网站中到达该部分时才显示效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40895232/