2011-03-03 64 views
0


如何用一個按鈕切換文本大小? 在14點和16點之間切換會很酷。
由於jQuery單鍵切換文本

實施例 '兩個按鈕沒有切換'

<!DOCTYPE html PUBLIC "> 
<head> 
<script type="text/javascript" src="js/jquery-1.4.min.js"></script> 
<script type='text/javascript'> 
$(function(){ 
$('input').click(function(){ 
var ourText = $('p'); 
var currFontSize = ourText.css('fontSize'); 
var finalNum = parseFloat(currFontSize, 10); 
var stringEnding = currFontSize.slice(-2); 
if(this.id == 'large') { 
finalNum *= 1.2; 
} 
else if (this.id == 'small'){ 
finalNum /=1.2; 
} 
ourText.css('fontSize', finalNum + stringEnding); 
}); 
}); 
</script> 
</head> 

<body> 
<h2>Toggle Text jQuery Single Button? </h2> 

<!--NEED A SINGLE BUTTON TOGGLE--> 
<input type='button' value='< text small' id='small' /> 
<input type='button' value='text large>' id='large' /> 

<p>My Text!!!</p> 
</body> 
</html> 

回答

5
var fontSizes = [14, 16]; 
    $('input').click(function() { 
    $('p').css('font-size', fontSizes[0] + 'pt'); 
    fontSizes.reverse(); 
    }) 

或者,使用CSS:

<style type="text/css"> 
    p { 
    font-size: 14pt; 
    }  
    p.larger { 
    font-size: 16pt; 
    } 
</style> 

<script>  
    $('input').click(function() { 
    $('p').toggleClass('larger'); 
    }) 
</script> 
1

CSS
.small-text { font-size: 14pt; } 
.large-text { font-size: 16pt; } 

的Javascript

$(function(){ 
    var textSizeButton = $("#text-size-toggle"); 
    textSizeButton.click(function(){ 
     var body = $('body'); // or any selector you want 
     if (body.hasClass('small-text')) { 
      body 
       .removeClass('small-text') 
       .addClass('large-text'); 
      textSizeButton.setAttr('value', 'Go smaller'); 
     } 
     else { 
      body 
       .removeClass('large-text') 
       .addClass('small-text'); 
      textSizeButton.setAttr('value', 'Go larger'); 
     } 
    }); 
}); 

HTML

<input type="button" id="text-size-toggle" value="Go larger" /> 
1

使用jQuery UI的,比你可以從一個複選框,使一個按鈕。你可以在這裏下載:http://jqueryui.com/download

$("#check").button(); 
    $("#check").click(function() { 
     var ourText = $('p'); 
     if ($(this).is(':checked')) { 
      ourText.css('fontSize', 'large') 
     } 
     else { 
      ourText.css('fontSize', 'small') 
     } 
    });