2017-08-02 11 views
-2

私はユーザが自分のウェブサイトでフォントサイズを変更できるようにしています。ユーザーがidをクリックするたびに"Large" 1pxがフォントに追加され、同様に"small" 1pxがクリックされると減少します。イベントのバインドとアンバインドjQuery

また、ユーザーは同じボタンを2回クリックすることはできません。そのボタンのクリックイベントはバインド解除されていますが、他のボタンをクリックした後はクリックできます。ここではバインドクリックイベントを使用していますが、バインド解除後に動作するようです。ここ

$("#large").on("click", function() { 
 
    $(this).unbind('click'); 
 
    $("#medium").bind('click'); 
 
    $("#small").bind('click'); 
 
    $("div").children().each(function() { 
 
     var size = parseInt($(this).css("font-size")); 
 
     size = size + 1 + "px"; 
 
     $(this).css({ 
 
      'font-size': size 
 
     }); 
 
    }); 
 

 
}); 
 

 
$("#medium").on("click", function() { 
 
    $(this).unbind('click'); 
 
    $("#large").bind('click'); 
 
    $("#small").bind('click'); 
 
    $("div").children().each(function() { 
 
     var size = parseInt($(this).css("font-size")); 
 
     size = size + 0 + "px"; 
 
     $(this).css({ 
 
      'font-size': size 
 
     }); 
 
    }); 
 
}); 
 

 
$("#small").on("click", function() { 
 
    $(this).unbind('click'); 
 
    $("#medium").bind('click'); 
 
    $("#small").bind('click'); 
 
    $("div").children().each(function() { 
 
     var size = parseInt($(this).css("font-size")); 
 
     size = size - 3 + "px"; 
 
     $(this).css({ 
 
      'font-size': size 
 
     }); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<a href="" id="large">Large</a> 
 
<a href="" id="medium">Medium</a> 
 
<a href="" id="small">Small</a> 
 

 
    <div> 
 
     <p>Lorem ispsum dolor</p> 
 
     <h1>Lorem ispsum dolor Lorem ispsum dolor Lorem ispsum dolor</h1> 
 
     <h3>Lorem Ipsum</h3> 
 
    </div> 
 
    
 

 
     
 

 
<!-- begin snippet: js hide: false console: true babel: false -->

フィドルです:巨大なコードの重複で

https://jsfiddle.net/Nag/etsbapgu/

答えて

0

あなたのアプローチの結果は。より良い選択肢は、data- *属性にfont diffを格納し、hanlderを一度バインドすることです。次に、ハンドラによって設定された直前の差分をチェックします。

これにより、コードに触れることなく、将来的に(Extra Small、Extra Largeなど)さらに多くのリンクを追加することができます。

$('[data-font]').click((function(current){ 
 

 
    return function(e) { 
 
    var $this = $(this), 
 
     font = parseInt($this.data('font')), 
 
     // remove previous diff and add new 
 
     diff = -current + font; 
 
      
 
    e.preventDefault(); 
 
      
 
    // same button click 
 
    if(current === font) return 
 
      
 
    // save for the next call 
 
    current = font; 
 
     
 
    $('div').children().css('font-size', function() { 
 
     return parseFloat($(this).css('font-size')) + diff + 'px'; 
 
    }) 
 
     
 
    } 
 
    
 
}(0)))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<a href="" data-font="+3">Large</a> 
 
<a href="" data-font="0">Medium</a> 
 
<a href="" data-font="-3">Small</a> 
 

 
    <div> 
 
     <p>Lorem ispsum dolor</p> 
 
     <h1>Lorem ispsum dolor Lorem ispsum dolor Lorem ispsum dolor</h1> 
 
     <h3>Lorem Ipsum</h3> 
 
    </div> 
 

関連する問題