簡體   English   中英

如何僅針對某些元素覆蓋 javascript 單擊事件?

[英]How can I override javascript click event for only certain elements?

我正在學習 codrops 的教程。 每個項目都有一個 hover 事件,以及一個觸發anime.js function 的點擊事件。

我正在嘗試這樣做,因此某些項目(網格單元)在單擊時不會觸發anime.js function,但 hover function 仍然有效。

我試過簡單的 css 指針事件,但這會禁用 hover function。

我已經在 JS 中將這兩個組構建為單獨的項目,但是 animation 的工作方式不同(它錯開了兩個不同的類)。

我已經嘗試過阻止默認的 javascript 行為,但它似乎對代碼沒有影響。

幫助!!!

我已經制作了一個功能正常的代碼筆 - 在該選項中,我試圖禁用任何具有 id="noClick" 的網格項目的點擊事件 - 無濟於事。

$('noClick').observe('click', function(event) {
    Event.stop(event); 
});

這是創建事件的主要 function

this.DOM.items.forEach((item, pos) => {
                // The item's title.
                const title = item.dataset.title;
                // Show the title next to the cursor.
                item.addEventListener('mouseenter', () => cursor.setTitle(title));
                item.addEventListener('click', () => {
                    // Position of the clicked item
                    this.pos = pos;
                    this.title = title;
                    // Start the effect and show the content behind
                    this.showContent();
                    // Force to show the title next to the cursor (it might not update because of the grid animation - the item under the mouse can be a different one than the one the user moved the mouse to)
                    cursor.setTitle(title);
                });
            });

“項目”在哪里

this.DOM.grid = this.DOM.el.querySelector('.grid');
            // Thr grid items
            this.DOM.items = [...this.DOM.grid.children];
            // totla number of grid items
            this.itemsTotal = this.DOM.items.length;

我試圖創建多個項目

 this.DOM.grid = this.DOM.el.querySelector('.grid');
            this.DOM.yesClick = this.DOM.el.querySelector('.yes-click'); 
            this.DOM.yesClickTwo = this.DOM.el.querySelector('.yes-click-2');            
            this.DOM.noClick = this.DOM.el.querySelector('.no-click');

            // Thr grid items
            this.DOM.items = [...this.DOM.yesClick.children, ...this.DOM.yesClickTwo.children];
            this.DOM.itemsNo = [...this.DOM.noClick.children];
            this.DOM.allItems = [...this.DOM.noClick.children, ...this.DOM.yesClick.children, ...this.DOM.yesClickTwo.children];


            // totla number of grid items
            this.itemsTotal = this.DOM.allItems.length;

這有效,但與動畫混淆。

這是代碼筆

我覺得這真的很簡單,我錯過了一些東西。 希望學習,因此將不勝感激推動正確的方向或任何幫助!

1.您有多個具有相同 ID 的元素。 但 ID 屬性必須是唯一的。

2.您使用$('noClick') ,但 ID 選擇器看起來像#noClick

如果要標記少量元素,請使用 class 和 select ,如.elementclass 元素可以有多個類,用空格分隔。

您的選擇器似乎不正確,因此您需要 #noClick 或 .noClick 作為選擇器,但是您可以阻止 javascript 像這樣冒泡:-

$(".noClick").click(function(e) {
   // Do something?
   e.stopPropagation();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM