カスタムデータ属性「data-*」を使って要素の表示非表示を制御する
色々な要素を表示、非表示する関数を作ったので公開
CSS
- function hideAndShow(op){
- var target = 'target', // 対象のグループ名
- show = 'show', // 対象の名前
- group = 'group', // 被対象のグループ名
- name = 'name', // 被対象の名前
- active = 'is-active', // アクティブクラス
- inactive = 'is-inactive'; // 非アクティブクラス
- // 対象グループを非表示
- function toHide(tag){
- $('[data-'+group+'*="'+tag+'"]').hide();
- }
- // 対象グループの対象ネームを表示
- function toShow(g,t){
- $('[data-'+group+'*="'+g+'"][data-'+name+'*="'+t+'"]').show();
- }
- // クラスを変更
- function changeClass(e,g){
- $('[data-'+target+'*="'+g+'"]').not(e).removeClass(active).addClass(inactive);
- $(e).removeClass(inactive).addClass(active);
- }
- // 実行内容
- function allPractice(e){
- var d = e.currentTarget.dataset,
- splitTarget = d[target].split(','),
- splitShow = d[show].split(',');
- $.each(splitTarget,function(i,group){
- toHide(group);
- $.each(splitShow,function(j,name){
- toShow(group,name);
- if(op.addClass !== void 0 && $.inArray(group,op.addClass) >= 0)changeClass(e.target,group);
- });
- });
- }
- // 対象の設定されたタグをクリックで実行
- $('[data-'+target+']').on('click',allPractice);
- // 全てのグループを非表示
- $('[data-'+group+']').hide();
- // 初期表示
- if(op.defaultShow !== void 0){
- $.each(op.defaultShow,function(i,v){
- toShow(v.group,v.name);
- });
- }
- }
- $(function(){
- hideAndShow({
- addClass : ['test'], // 起動する要素のクラスを変更するグループ名
- defaultShow : [{ // 初期表示
- group : 'test', // グループ名
- name : 'tag1' // 名前
- }]
- });
- });
コメント一覧
まだ、コメントがありません