参考: jsFiddle
font-size
我已经修改了您原来的想法,并说明了当使用 jQuery获取 CSS 时,单元(例如, px
)得到正确处理。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'));