跟踪类是否在视口中

时间:2017-08-04 15:55:28

标签: javascript html

我想在用户在视口中有一个类时触发一个触发器。理想情况下,这将适用于每个部分标题;

<h2 class="section-heading">About</h2>

如果该类落入视口,我想按照以下方式触发虚拟页面视图;

<script type="text/javascript">
   dataLayer.push({
      'event':'VirtualPageview',
      'virtualPageURL':{{Page Hostname}},
      'virtualPageTitle':{{Page URL}}
});
</script>

如果有人知道如何设置它,我将非常感激。这是一个单页的网站。

2 个答案:

答案 0 :(得分:1)

更新!

使用新的Intersection Observer API。除了Safari之外的所有现代浏览器都支持它:http://caniuse.com/#feat=intersectionobserver

这是IE和Safari的填充:https://github.com/w3c/IntersectionObserver/tree/gh-pages/polyfill

旧回答:

我在几个项目中使用waypoints plugin,效果很好。

var waypoint = new Waypoint({
  element: document.getElementsByClassName('section-heading'),
  handler: function(direction) {
    alert('You have scrolled to a thing')
  }
})

以下是完整的文档:http://imakewebthings.com/waypoints/guides/getting-started/

希望这有帮助!

答案 1 :(得分:0)

IntersectionObserver API绝对是你做这件事的最好机会。

它得到了大多数浏览器的支持,对于那些尚不支持它的少数人来说有polyfill

谷歌开发者博客上的

This post在向您展示其基本用途方面肯定会有所帮助,大致可能是这样的:

var io = new IntersectionObserver(
    entries => {
        //Do something with the entries, e.g. push to the dataLayer
        console.log(entries);
    }
); 

io.observe(document.getElementsByClassName('section-heading'));

这样,只要.section-heading进入视口,你就会注册观察者来执行回调,这应该是你愿意完成的。