2017-08-14 20 views
0

這個slider正在一個動畫循環中運行,除非點擊頂部的一個點。然後,動畫元素(<span>點和<figure>)會獲得停止動畫的樣式。爲什麼點擊事件沒有達到<body>?

<section id="slider"> 
    <span class="control" tabindex="1"></span> 
    <span class="control" tabindex="2"></span> 
    <span class="control" tabindex="3"></span> 
    <figure class="slide"> 
     <!--Image 1---> 
    </figure> 
    <figure class="slide"> 
     <!--Image 2---> 
    </figure> 
    <figure class="slide"> 
     <!--Image 3---> 
    </section> 

腳本:動畫停止

window.onload = function() { 
    var slider = document.querySelector('#slider'); 
    var animated = slider.querySelectorAll('.control, .slide'); 

    function switchAll (focus) { 
     animated.forEach(function (el) { 
      el.style['animation-name'] = focus ? 'none' : null; 
     }); 
    } 

    document.querySelector('body').addEventListener('click', function (e) { 
     switchAll(slider.querySelector('.control:focus')); 
    }); 
}; 

後,如果其他的東西比點被點擊的時候,應該重新啓動(讓他們鬆焦點)。但是,在火狐上的僅當點擊超出#slider時纔有效。

在當前顯示的<figure>內部單擊可讓它消失 - 這是預期的CSS行爲,因爲沒有點具有焦點。但動畫不會重新啓動;第一個click事件沒有達到<body>。只有第二次點擊觸發事件偵聽器。

我也嘗試附加事件到#slider,但結果是一樣的。看起來好像事件不會冒泡過去的元素,附加在這些作品上,但顯然是一種劣質的解決方案。

無論如何,我想了解會發生什麼事件。

+0

事件本身_does_到達'body'(你可以通過在click處理程序中添加'console.log(e)'來確認它),但是''.control:focus''沒有選擇任何東西,因爲沒有設置tabindex'價值似乎不足以使諸如「span」這樣的非交互式元素成爲可聚焦的。使用'tabindex = -1',它們變得可以聚焦,並且點擊改變它們的行爲(在這個改變之後動畫看起來有點奇怪)。 –

+0

Chrome瀏覽器似乎需要tabindex編號,在Firefox上它可以被忽略。我描述的問題似乎是FF特定的。 - 你稱之爲「有點奇怪」的預期行爲順便說一句。 – ccprog

回答

0

我好像掉進這個陷阱:Blur event stops click event from working?

控制失去焦點的時刻,滑板移動可視區域之外,並且點擊時不打它。但它也沒有觸及背景;它確實似乎點擊被主動取消。

解決方案是將動畫的運行與單擊事件相結合,但與焦點/模糊事件相結合。

相關問題