javascript forEach-在所有按钮上添加addEventListener

javascript forEach-在所有按钮上添加addEventListener,javascript,html,Javascript,Html,我不太熟悉javascript,所以我正在寻求一些帮助。 我正在使用Codrops(3D网格效果-)上的脚本 正如预期的那样,一切正常,但我正试图“修改”它以满足我的需要 基本上,我想触发“效果”,不是点击整个容器,而是点击其中的一个按钮 我使用的结构是: <section class="grid3d vertical" id="grid3d"> <div class="grid-wrap"> <div class="

我不太熟悉javascript,所以我正在寻求一些帮助。 我正在使用Codrops(3D网格效果-)上的脚本

正如预期的那样,一切正常,但我正试图“修改”它以满足我的需要

基本上,我想触发“效果”,不是点击整个容器,而是点击其中的一个按钮

我使用的结构是:

    <section class="grid3d vertical" id="grid3d">
        <div class="grid-wrap">
            <div class="grid">
                <div class="box"><div class="btn-click-me">Click to Show</div></div>
                <div class="box"><div class="btn-click-me">Click to Show</div></div>
                <div class="box"><div class="btn-click-me">Click to Show</div></div>

            </div>
        </div>
        <div class="content">
            <div>
                <div class="dummy-img"></div>
                <p class="dummy-text">Some text</p>
                <p class="dummy-text">Some more text</p>
            </div>
            <div>
                <!-- ... -->
            </div>
            <!-- ... -->
            <span class="loading"></span>
            <span class="icon close-content"></span>
        </div>
    </section>

<script>
            new grid3D( document.getElementById( 'grid3d' ) );
        </script>

点击显示
点击显示
点击显示

一些文本

更多文本

新的grid3D(document.getElementById('grid3D');
脚本(js)是

/**
*grid3d.js v1.0.0
* http://www.codrops.com
*
*根据麻省理工学院许可证授权。
* http://www.opensource.org/licenses/mit-license.php
* 
*版权所有2014,Codrops
* http://www.codrops.com
*/
;(功能(窗口){
"严格使用",;
功能grid3D(el,选项){
this.el=el;
this.options=extend({},this.options);
扩展(这个。选项,选项);
这个;
}
//您可能想要配置的任何选项
grid3D.prototype.options={};
prototype.\u init=function(){
//网格包装器
this.gridWrap=this.el.querySelector('div.grid-wrap');
//网格元素
this.grid=this.gridWrap.querySelector('div.grid');
//主要网格项目
this.gridItems=[].slice.call(this.grid.children);
//网格项的默认大小
this.itemSize={width:this.gridItems[0].offsetWidth,height:this.gridItems[0].offsetHeight};
//内容
this.contentEl=this.el.querySelector('div.content');
//内容项
this.contentItems=[].slice.call(this.contentEl.children);
//近内容交叉
this.close=this.contentEl.querySelector('span.close content');
//装载指示器
this.loader=this.contentEl.querySelector('span.loader');
//支持:支持指针事件、转换和三维变换
this.support=support.pointerevents&&support.cstranitions&&support.cstransforms3d;
//初始化事件
这个;
};
prototype.\u initEvents=function(){
var self=这个;
//单击主网格项时打开内容元素
this.gridItems.forEach(函数(item,idx){
item.addEventListener('click',函数(){
自我展示内容(idx);
} );
} );
//关闭内容元素
this.close.addEventListener('click',function(){
self._hideContent();
} );
如果(这个支持){
//调整窗口大小
addEventListener('resize',function(){self.\u resizeHandler();});
//动画运行时防止滚动的技巧(仅打开)
//这可以防止占位符的背面不会以错误的方式放置
addEventListener('scroll',function(){
如果(自我激励){
scrollTo(self.scrollPosition?self.scrollPosition.x:0,self.scrollPosition?self.scrollPosition.y:0);
}
否则{
self.scrollPosition={x:window.pageXOffset | | | docElem.scrollLeft,y:window.pageYOffset | | docElem.scrollTop};
//在滚动页面时更改网格透视图原点
self._scrollHandler();
}
});
}
};
//创建占位符并将其设置为全屏动画
//在动画结束时,将显示内容
//加载指示器将出现1秒,以模拟加载周期
grid3D.prototype.\u showContent=函数(pos){
如果(这个是动画){
返回false;
}
this.isAnimating=true;
var self=这个,
loadContent=函数(){
//模拟加载。。。
setTimeout(函数(){
//隐藏装载机
classie.removeClass(self.loader,'show');
//在转换结束时,将类“show”设置为相应的内容项
classie.addClass(self.contentItems[pos],“show”);
}, 1000 );
//显示内容区
classie.addClass(self.contentEl,“show”);
//显示加载器
classie.addClass(self.loader,'show');
classie.addClass(document.body,'noscorl');
自我美化=错误;
};
//如果不支持,只需加载内容(简单回退-根本没有动画)
如果(!this.support){
loadContent();
返回false;
}
var currentItem=this.gridItems[pos],
itemContent=currentItem.innerHTML;
//创建占位符
this.placeholder=this.\u createPlaceholder(itemContent);
//将占位符的顶部和左侧设置为单击的网格项的顶部和左侧(相对于网格)
this.placeholder.style.left=currentItem.offsetLeft+'px';
this.placeholder.style.top=currentItem.offsetTop+'px';
//将占位符附加到网格
this.grid.appendChild(this.placeholder);
//并将其动画化
var animFn=函数(){
//将类“活动”赋予当前网格项(隐藏它)
classie.addClass(当前项“活动”);
//将类“查看完整”添加到网格换行
古典的
/**
 * grid3d.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Copyright 2014, Codrops
 * http://www.codrops.com
 */
;( function( window ) {

    'use strict';

    function grid3D( el, options ) {
        this.el = el;
        this.options = extend( {}, this.options );
        extend( this.options, options );
        this._init();
    }

    // any options you might want to configure
    grid3D.prototype.options = {};

    grid3D.prototype._init = function() {
        // grid wrapper
        this.gridWrap = this.el.querySelector( 'div.grid-wrap' );
        // grid element
        this.grid = this.gridWrap.querySelector( 'div.grid' );
        // main grid items
        this.gridItems = [].slice.call( this.grid.children );
        // default sizes for grid items
        this.itemSize = { width : this.gridItems[0].offsetWidth, height : this.gridItems[0].offsetHeight };
        // content
        this.contentEl = this.el.querySelector( 'div.content' );
        // content items
        this.contentItems = [].slice.call( this.contentEl.children );
        // close content cross
        this.close = this.contentEl.querySelector( 'span.close-content' );
        // loading indicator
        this.loader = this.contentEl.querySelector( 'span.loading' );
        // support: support for pointer events, transitions and 3d transforms
        this.support = support.pointerevents && support.csstransitions && support.csstransforms3d;
        // init events
        this._initEvents();
    };

    grid3D.prototype._initEvents = function() {
        var self = this;

        // open the content element when clicking on the main grid items
        this.gridItems.forEach( function( item, idx ) {
            item.addEventListener( 'click', function() {
                self._showContent( idx );
            } );
        } );

        // close the content element
        this.close.addEventListener( 'click', function() {
            self._hideContent();
        } );

        if( this.support ) {
            // window resize
            window.addEventListener( 'resize', function() { self._resizeHandler(); } );

            // trick to prevent scrolling when animation is running (opening only)
            // this prevents that the back of the placeholder does not stay positioned in a wrong way
            window.addEventListener( 'scroll', function() {
                if ( self.isAnimating ) {
                    window.scrollTo( self.scrollPosition ? self.scrollPosition.x : 0, self.scrollPosition ? self.scrollPosition.y : 0 );
                }
                else {
                    self.scrollPosition = { x : window.pageXOffset || docElem.scrollLeft, y : window.pageYOffset || docElem.scrollTop };
                    // change the grid perspective origin as we scroll the page
                    self._scrollHandler();
                }
            });
        }
    };

    // creates placeholder and animates it to fullscreen
    // in the end of the animation the content is shown
    // a loading indicator will appear for 1 second to simulate a loading period
    grid3D.prototype._showContent = function( pos ) {
        if( this.isAnimating ) {
            return false;
        }
        this.isAnimating = true;

        var self = this,
            loadContent = function() {
                // simulating loading...
                setTimeout( function() {
                    // hide loader
                    classie.removeClass( self.loader, 'show' );
                    // in the end of the transition set class "show" to respective content item
                    classie.addClass( self.contentItems[ pos ], 'show' );
                }, 1000 );
                // show content area
                classie.addClass( self.contentEl, 'show' );
                // show loader
                classie.addClass( self.loader, 'show' );
                classie.addClass( document.body, 'noscroll' );
                self.isAnimating = false;
            };

        // if no support just load the content (simple fallback - no animation at all)
        if( !this.support ) {
            loadContent();
            return false;
        }

        var currentItem = this.gridItems[ pos ],
            itemContent = currentItem.innerHTML;

        // create the placeholder
        this.placeholder = this._createPlaceholder(itemContent );

        // set the top and left of the placeholder to the top and left of the clicked grid item (relative to the grid)
        this.placeholder.style.left = currentItem.offsetLeft + 'px';
        this.placeholder.style.top = currentItem.offsetTop + 'px';

        // append placeholder to the grid
        this.grid.appendChild( this.placeholder );

        // and animate it
        var animFn = function() {
            // give class "active" to current grid item (hides it)
            classie.addClass( currentItem, 'active' );
            // add class "view-full" to the grid-wrap
            classie.addClass( self.gridWrap, 'view-full' );
            // set width/height/left/top of placeholder
            self._resizePlaceholder();
            var onEndTransitionFn = function( ev ) {
                if( ev.propertyName.indexOf( 'transform' ) === -1 ) return false;
                this.removeEventListener( transEndEventName, onEndTransitionFn );
                loadContent();
            };
            self.placeholder.addEventListener( transEndEventName, onEndTransitionFn );
        };

        setTimeout( animFn, 25 );
    };

    grid3D.prototype._hideContent = function() {
        var self = this,
            contentItem = this.el.querySelector( 'div.content > .show' ),
            currentItem = this.gridItems[ this.contentItems.indexOf( contentItem ) ];

        classie.removeClass( contentItem, 'show' );
        classie.removeClass( this.contentEl, 'show' );
        // without the timeout there seems to be some problem in firefox
        setTimeout( function() { classie.removeClass( document.body, 'noscroll' ); }, 25 );
        // that's it for no support..
        if( !this.support ) return false;

        classie.removeClass( this.gridWrap, 'view-full' );

        // reset placeholder style values
        this.placeholder.style.left = currentItem.offsetLeft + 'px';
        this.placeholder.style.top = currentItem.offsetTop + 'px';
        this.placeholder.style.width = this.itemSize.width + 'px';
        this.placeholder.style.height = this.itemSize.height + 'px';

        var onEndPlaceholderTransFn = function( ev ) {
            this.removeEventListener( transEndEventName, onEndPlaceholderTransFn );
            // remove placeholder from grid
            self.placeholder.parentNode.removeChild( self.placeholder );
            // show grid item again
            classie.removeClass( currentItem, 'active' );
        };
        this.placeholder.addEventListener( transEndEventName, onEndPlaceholderTransFn );
    }

    // function to create the placeholder
    /*
    <div class="placeholder">
        <div class="front">[content]</div>
        <div class="back"></div>
    </div>
    */
    grid3D.prototype._createPlaceholder = function( content ) {
        var front = document.createElement( 'div' );
        front.className = 'front';
        front.innerHTML = content;
        var back = document.createElement( 'div' );
        back.className = 'back';
        back.innerHTML = '&nbsp;';
        var placeholder = document.createElement( 'div' );
        placeholder.className = 'placeholder';
        placeholder.appendChild( front );
        placeholder.appendChild( back );
        return placeholder;
    };

    grid3D.prototype._scrollHandler = function() {
        var self = this;
        if( !this.didScroll ) {
            this.didScroll = true;
            setTimeout( function() { self._scrollPage(); }, 60 );
        }
    };

    // changes the grid perspective origin as we scroll the page
    grid3D.prototype._scrollPage = function() {
        var perspY = scrollY() + getViewportH() / 2;
        this.gridWrap.style.WebkitPerspectiveOrigin = '50% ' + perspY + 'px';
        this.gridWrap.style.MozPerspectiveOrigin = '50% ' + perspY + 'px';
        this.gridWrap.style.perspectiveOrigin = '50% ' + perspY + 'px';
        this.didScroll = false;
    };

    grid3D.prototype._resizeHandler = function() {
        var self = this;
        function delayed() {
            self._resizePlaceholder();
            self._scrollPage();
            self._resizeTimeout = null;
        }
        if ( this._resizeTimeout ) {
            clearTimeout( this._resizeTimeout );
        }
        this._resizeTimeout = setTimeout( delayed, 50 );
    }

    grid3D.prototype._resizePlaceholder = function() {
        // need to recalculate all these values as the size of the window changes
        this.itemSize = { width : this.gridItems[0].offsetWidth, height : this.gridItems[0].offsetHeight };
        if( this.placeholder ) {
            // set the placeholders top to "0 - grid offsetTop" and left to "0 - grid offsetLeft"
            this.placeholder.style.left = Number( -1 * ( this.grid.offsetLeft - scrollX() ) ) + 'px';
            this.placeholder.style.top = Number( -1 * ( this.grid.offsetTop - scrollY() ) ) + 'px';
            // set the placeholders width to windows width and height to windows height
            this.placeholder.style.width = getViewportW() + 'px';
            this.placeholder.style.height = getViewportH() + 'px';
        }
    }

    // add to global namespace
    window.grid3D = grid3D;

})( window );
    <div class="grid-wrap">
        <div class="grid">
            <div class="box"><div class="btn-click-me">Click to Show</div></div>
            <div class="box"><div class="btn-click-me">Click to Show</div></div>
            <div class="box"><div class="btn-click-me">Click to Show</div></div>

        </div>
    </div>
item.children[0].addEventListener( 'click', function() {
item.getElementsByClassName('btn-click-me')[0].addEventListener( 'click', function() {
    // get grid buttons and then make an iterable array out of them        
    this.gridButtons = this.el.querySelectorAll('button.btn-click-me');
    this.gridButtonItems = [].slice.call(this.gridButtons);
    // open the content element when clicking on the buttonsItems
    this.gridButtonItems.forEach(function (item, idx) {
        item.addEventListener('click', function () {
            self._showContent(idx);
        });
    });
var buttons = document.querySelectorAll('.btn-click-me');
for (var i = 0; i < buttons.length; i++) {
    var self = buttons[i];

    self.addEventListener('click', function (event) {  
        // prevent browser's default action
        event.preventDefault();

        // call your awesome function here
        MyAwesomeFunction(this); // 'this' refers to the current button on for loop
    }, false);
}