参考: jsFiddle
私はあなたの元のアイデアを修正し、font-size
jQuery を使用して CSS を取得するときにユニット (たとえば、px
) が正しく処理されるという事実を説明しました。font-size は、maxSize
変数で指定した最大値に「制限」されます。
HTML:
<div class="resize-larger">[+] Increase Font Size</div> <br /><br />
<p class="one-third">This is a test</p> <br /><br />
<p class="two-thirds">This is a test</p> <br /><br />
<br /><br /><br />
<div id="results">Current font-size: </div>
CSS:
.resize-larger {
width: 175px;
height: 40px;
line-height: 40px;
background-color: yellow;
color: red;
border: 1px solid red;
margin: 10px;
text-align: center;
}
p {
font-size: 12px;
font-family: Arial;
font-weight: bold;
color: blue;
}
jQuery:
// Reset Font Size
var targetContainers = $('.one-third, .two-thirds');
// Increase Font Size
$(".resize-larger").click(function() {
var currentFontSize = parseFloat($(targetContainers).css('font-size'), 10);
var maxSize = 18;
// This 'if' is 'true' when var maxsize (a number) is larger than var currentFontsize (also a number).
if (currentFontSize < maxSize) {
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum * 1.2;
// Once the calculated newFontSize value is obtained, it will be capped to maxSize if it's larger.
if (newFontSize > maxSize) {
newFontSize = maxSize;
}
// This will show the current font-size in the results div.
$('#results').html('Current font-size: ' + newFontSize + 'px');
// Apply the newFontSize value, adding in unit of 'px' to the current value.
$(targetContainers).css('font-size', newFontSize + 'px');
return false;
}
});
// On page load, the results div will be populated with the current font size.
$('#results').html('Current font-size: ' + $(targetContainers).css('font-size'));