2017-08-02 158 views
-2

我允许用户在我的网站上更改字体大小,每次用户点击ID "Large" 1px被添加到字体中,并且同样点击"small" 1px被降低。绑定和解除绑定事件jQuery

此外,用户不允许点击同一个按钮两次,所以我解开了该按钮上的点击事件,但可以点击其他按钮后点击,这里我使用绑定点击事件,但它没有'在解除绑定后似乎工作。

$("#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- *属性中并绑定一次hanlder。然后检查处理程序设置的前一个比较。

这将允许您在将来添加更多链接(比如超小型或特大型)而不用触摸代码。

$('[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>