【发布时间】:2018-06-21 03:21:45
【问题描述】:
我正在使用 facebook 像素代码来确定用户何时阅读了整篇文章。我有一个无限的博客,所以当用户向下滚动页面时 URL 会发生变化。我目前有一个功能可以在用户到达页面末尾时运行一次,但我需要对其进行修改,以便如果 URL 发生更改,该功能将被重置并可以再次运行。这是我当前的代码。
// determine the position of element
jQuery.fn.isInViewport = function() {
var elementTop = jQuery(this).offset().top;
var elementBottom = elementTop + jQuery(this).outerHeight();
var viewportTop = jQuery(window).scrollTop();
var viewportBottom = viewportTop + jQuery(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
// grab the current URL
var originalURL = window.location.href;
// check to see if element is in viewport
jQuery(window).on('resize scroll', function() {
var currentURL = '';
jQuery('.end-of-content-icon').each(function() {
if (jQuery(this).isInViewport()) {
currentURL = window.location.href;
if(originalURL !== currentURL) {
canOnlyFireOnce();
originalURL = currentURL;
}
}
});
});
// function to only fire once (courtesy of David Walsh)
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
// Usage
var canOnlyFireOnce = once(function() {
fbq('track', 'Lead');
});
【问题讨论】:
-
once()只触发一次,因为它将自己设置为null。如果您想多次运行它,则不需要它。尝试将canOnlyFireOnce();替换为fbq('track', 'Lead');你的条件if(originalURL !== currentURL)运行它应该足够了。 -
不幸的是,这不起作用,因为代码在滚动时工作,因此该函数在用户滚动时被多次调用
-
是的,每次轮子旋转都会触发 10~12 次滚动。但条件是“过滤”。
标签: javascript jquery facebook facebook-pixel