这是一款仿商城产品列表的模式切换的插件,使用了css3和javascript技术制作。
HTML
<div id="cbp-vm" class="cbp-vm-switcher cbp-vm-view-grid"> <div class="cbp-vm-options"> <a href="#" class="cbp-vm-icon cbp-vm-grid cbp-vm-selected" data-view="cbp-vm-view-grid">Grid View</a> <a href="#" class="cbp-vm-icon cbp-vm-list" data-view="cbp-vm-view-list">List View</a> </div> <ul> <li> <a class="cbp-vm-image" href="#"><img src="images/1.png"></a> <h3 class="cbp-vm-title">Silver beet</h3> <div class="cbp-vm-price">$19.90</div> <div class="cbp-vm-details"> Silver beet shallot wakame tomatillo salsify mung bean beetroot groundnut. </div> <a class="cbp-vm-icon cbp-vm-add" href="#">Add to cart</a> </li> <li> <!-- ... --> </li> <!-- ... --> </ul> </div>
核心javascript部分代码。
(function() { var container = document.getElementById( 'cbp-vm' ), optionSwitch = Array.prototype.slice.call( container.querySelectorAll( 'div.cbp-vm-options > a' ) ); function init() { optionSwitch.forEach( function( el, i ) { el.addEventListener( 'click', function( ev ) { ev.preventDefault(); _switch( this ); }, false ); } ); } function _switch( opt ) { // remove other view classes and any any selected option optionSwitch.forEach(function(el) { classie.remove( container, el.getAttribute( 'data-view' ) ); classie.remove( el, 'cbp-vm-selected' ); }); // add the view class for this option classie.add( container, opt.getAttribute( 'data-view' ) ); // this option stays selected classie.add( opt, 'cbp-vm-selected' ); } init(); })();