我想要一些jquery代码,它会增加或减少字体。 我尝试了一些代码,但运行不顺利。
这是我演示的link(我第一次使用小提琴,所以请你根据需要设置)
我这里有不同大小的字体,但在增加字体大小时,它会使所有字体大小相同。那么如何修复呢?
我的代码:
<div id='contents'><div><strong>Lorem Ipsum</strong> is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry's standard dummy
<div><font face="Comic Sans MS" size="5" color="#c2c2c2">text ever since the 1500s, when an unknown printer took a galley of
type and scrambled it to make a type specimen book. It has survived not </font></div><font face="Comic Sans MS" size="5" color="#c2c2c2">
only five centuries, but also the leap into electronic typesetting,
remaining essentially unchanged. It was popularised in the 1960s with
the release of Letraset sheets containing Lorem Ipsum </font>passages, and more
recently with desktop publishing software like <font size="1">Aldus PageMaker
including versions of </font><div><font size="1">Lorem Ipsum. </font></div></div></div>
<a href="#" onclick="increaseFont()">increaseFont</a>
<a href="#" onclick="decreaseFont()">decreaseFont</a>
<script type="text/javascript">
var $ = jQuery
var section = '#contents *';
var originalFontSize = $(section).css('font-size');
var originalLineHeight = $(section).css('line-height');
function resetFont() {
$(section).css('font-size', originalFontSize);
$(section).css('font-size', originalLineHeight);
}
function increaseFont() {
var currentFontSize = $(section).css('font-size');
var currentLineHeight = $(section).css('line-height');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum * 1.2;
$(section).css('font-size', newFontSize);
var currentLineHeightNum = parseFloat(currentLineHeight, 10);
var newLineHeight = currentLineHeightNum * 0.1;
$(section).css('line-height', newLineHeight);
return false;
}
function decreaseFont() {
var currentFontSize = $(section).css('font-size');
var currentLineHeight = $(section).css('line-height');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum * 0.8;
$(section).css('font-size', newFontSize);
var currentLineHeightNum = parseFloat(currentLineHeight, 10);
var newLineHeight = currentLineHeightNum * 0.8;
$(section).css('line-height', newLineHeight);
return false;
}
</script>
答案 0 :(得分:1)
主要问题是您正在调用$(section).css(),它返回单个值(16px),但将其应用于所有部分。让你的代码工作并不太困难 - 你要做的就是调用$(section),但是使用.each()循环遍历每个部分并以这种方式更新值。
我已经更新了您的小提琴,其中更新了increaseFont函数以说明解决方法。希望这对你有帮助!
我所做的改变:
function increaseFont() {
$(section).each(function(idx, el){
var currentFontSize = $(this).css('font-size'),
currentLineHeight = $(this).css('line-height'),
currentFontSizeNum = parseFloat(currentFontSize, 10),
newFontSize = currentFontSizeNum * 1.2;
$(this).css('font-size', newFontSize);
var currentLineHeightNum = parseFloat(currentLineHeight, 10),
newLineHeight = currentLineHeightNum * 0.1;
$(this).css('line-height', newLineHeight);
});
}
Happy JavaScripting!