5

对于下面可能是一个简单的问题和令人震惊的javascript,请提前道歉;

我的问题如下,网站上有一个横幅,每隔几秒就会浏览四张图片。我正在尝试将“印象”推入数据层以供 GTM 拾取。为了显示下一张图片,它(不是我自己)将下一张横幅图片的 z-index 从 0 更改为 1。我最初试图让突变观察者只处理一张图像。这行得通,但我很快发现 z-index 值实际上改变了大约 3 次,然后才确定为 1,因此每次实际上触发了 3 次展示。然而,理想情况下,我希望通过查看父 div(并观察 childList)并且每个横幅图像只触发一次印象,但是当我尝试它只是说“提供的节点为空”时,我想知道它是否是与只有孩子的事实有关

横幅 HTML 是(当显示 imagePane2 时);

<div id="rotator_10690" class="imageRotator Homepage_Middle_Banner_Rotator">
<div class="imagePane Homepage_Middle_Banner_imagePane imagePane1" style="left: 0px; top: 0px; position: absolute; z-index: 0; opacity: 1; display: none;">
<div class="imagePane Homepage_Middle_Banner_imagePane imagePane2" style="left: 0px; top: 0px; position: absolute; z-index: 1;">
<div class="imagePane Homepage_Middle_Banner_imagePane imagePane3" style="left: 0px; top: 0px; position: absolute; z-index: 0; display: none;">
<div class="imagePane Homepage_Middle_Banner_imagePane imagePane4" style="left: 0px; top: 0px; position: absolute; z-index: 0; display: none;">

我的父 div 脚本是

<script>
// select the target node
var target = document.querySelector('.rotator_10690');

//call mutation observer api
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
 
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
      if(mutation.type==="attributes" && mutation.target.className.indexOf("imagePane")) {
         observer.disconnect();
         dataLayer.push({'event': 'paneImpression'});

      }
  });
});
 
var disconnect = observer.disconnect();
// configuration of the observer:
// pass in the target node, as well as the observer options
var config = { attributes: true, childList: true }
observer.observe(target, config);

而对于 imagePane2 (我在这里尝试了 mutation.some 并返回 false,试图在它收到第一个突变后停止它,但这不起作用。我也有 zIndex==="1" 在这里但是这仍然意味着每次触发 3 次或更多次展示。)。

<script>
// select the target node
var target = document.querySelector('.imagePane2');

//call mutation observer api
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
 
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.some(function(mutation) {
      if(mutation.type==="attributes" && mutation.target.className.indexOf("imagePane2")) {
         observer.disconnect();
         dataLayer.push({'event': 'paneImpression', 'pane': 'two'});

         return false;

      }
  });
});
 
var disconnect = observer.disconnect();
// configuration of the observer:
// pass in the target node, as well as the observer options
var config = { attributes: true }
observer.observe(target, config);


 

</script>

任何人都可以提供的任何帮助将不胜感激,我已经尝试过到处寻找但无法得到任何工作。

谢谢

4

1 回答 1

12
{ attributes: true, childList: true }

请求由于属性更改而发生的.rotator_10690突变,以及由于作为代码的子元素列表的更改而导致的突变。childList从字面上看,它会监听孩子列表的变化,而不是监听孩子本身的变化。

如果您想从本质上获得所有子节点的所有突变,就像 DOM 事件在树上传播一样,您需要添加

subtree: true  
于 2015-07-03T17:58:56.440 回答