最近,我遇到了在单页网站上跟踪用户的问题"使用Google Analytics。我想分享我的解决方案。请参阅下面的答案。
答案 0 :(得分:0)
最近,我遇到了在单页网站上跟踪用户的问题"使用Google Analytics。我想分享我的解决方案。
-----页面布局-----
1a. Header with logo and menu (links scroll page down to selected chapter)
2a. Section with big paralax bakground
2b. Chapter header <section><h2>Title 1</h2></section>
2c. Chapter's content <div>content</div>
3a. Section with big paralax bakground
3b. Chapter header <section><h2>Title 2</h2></section>
3c. Chapter's content <div>content</div>
...
Na. Section with big paralax bakground
Nb. Chapter header <section><h2>Title N</h2></section>
Nc. Chapter's content <div>content</div>
-----要求-----
----算法-----
----示例代码-----
<script type="text/javascript">
var scrollstat = []
// Preparing array of chapters and positions
$(document).ready(function() {
$("section").each(function() {
var ts = {};
ts["offset"] = $(this).offset();
str = $("h2", this).html();
ts["name"] = "SECTION-"+str.replace(" ","-")+"/";
ts["checked"] = false;
ts["timer"] = false;
scrollstat.push(ts);
});
});
//Checking that user is still on the same chapter
function doublecheck(ii) {
scrollpos = $(window).scrollTop();
max = scrollpos + 300;
min = scrollpos;
if (scrollstat[ii].checked == false && scrollstat[ii].offset.top > min
&& scrollstat[ii].offset.top < max) {
_gaq.push(['_trackPageview', (location.pathname + location.search
+ scrollstat[ii].name)]);
scrollstat[ii].checked = true;
}
console.log(scrollstat[ii].offset.top+','+min+','+max);
scrollstat[ii].timer = false;
}
//Separate function for setting timer to count 3s
//If user don't scroll to other chapter within this time
//event is reported to GA
function settimer(ii) {
scrollstat[ii].timer = true;
setTimeout(function() {doublecheck(ii);},3000);
}
//Handling scrolling event
$(window).scroll(function() {
scrollpos = $(window).scrollTop();
max = scrollpos + 300;
min = scrollpos;
for (index = 0; index < scrollstat.length; ++index) {
if (scrollstat[index].checked == false &&
scrollstat[index].timer == false &&
scrollstat[index].offset.top > min &&
scrollstat[index].offset.top < max) {
settimer(index);
}
}
});
</script>
MAX和MIN变量是通过实验估算的。在我的情况下,我假设章节标题必须滚动到屏幕的顶部。
作为上述脚本的结果,每个章节都作为单独的页面访问报告给GA,地址如下:&#34; / SECTION-chapter-title /&#34;