首页 > 解决方案 > 如何仅覆盖某些元素的 javascript 点击事件?

问题描述

我正在学习 codrops 的教程。每个项目都有一个悬停事件,以及一个触发anime.js函数的点击事件。

我正在尝试这样做,以便某些项目(网格单元格)在单击时不会触发anime.js 功能,但悬停功能仍然有效。

我尝试过简单的 css 指针事件,但这会禁用悬停功能。

我在 JS 中将这两个组构建为单独的项目,但是动画效果不一样(它错开了两个不同的类)。

我已经尝试过阻止默认的 javascript 行为,但它似乎对代码没有影响。

帮助!!!

我已经制作了一个功能正常的代码笔 - 在该选项中,我试图禁用 id="noClick" 的任何网格项目的点击事件 - 无济于事。

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

这是创建事件的主要功能

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;

这有效,但与动画混淆。

这是代码笔

我觉得这真的很简单,我错过了一些东西。希望学习,因此将不胜感激推动正确的方向或任何帮助!

标签: javascriptjqueryhtmlcssanime.js

解决方案


您的选择器似乎不正确,因此您需要 #noClick 或 .noClick 作为选择器,但是您可以像这样阻止 javascript 冒泡:-

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

推荐阅读