嗨,我想用 jQuery 逐步更改页面的字体大小,我该怎么做?
就像是:
$('body').css({'font-size':'+.01px'});
$('body').css({'font-size':'-.01px'});
嗨,我想用 jQuery 逐步更改页面的字体大小,我该怎么做?
就像是:
$('body').css({'font-size':'+.01px'});
$('body').css({'font-size':'-.01px'});
你可以这样做:
var fontSize = parseInt($("body").css("font-size"));
fontSize = fontSize + 1 + "px";
$("body").css({'font-size':fontSize});
您不能这样做,因为字体属性存储为字符串,如果您确定字体大小将以像素为单位,您可以这样做:
var fontSize = $('body').css('font-size').split('px')[0];
var fontInt = parseInt(fontSize) + 1;
fontSize = fontInt + 'px';
这可能需要稍微修改一下,我只是在没有测试的情况下编写了它。
它可能取决于哪个版本的 jquery,但我使用了以下
HTML
<input type="button" id="button" />
<div id="box"></div>
代码
$(document).ready(function() {
$("#button").click(function() {
$("#box").css("width","+=5");
});
});
试试这个:
jQuery("body *").css('font-size','+=1');
HTML
<input id="btn" type="button" value="Increase font" /> <br />
<div id="text" style="font-size:10px">Font size</div>
Javascript
$(document).ready(function() {
$('#btn').click(function() {
$('#text').css("font-size", function() {
return parseInt($(this).css('font-size')) + 1 + 'px';
});
});
});
演示:http: //jsfiddle.net/ynhat/CeaqU/
使用这样的东西
$(document).ready(function() {
$('id or class of what input').click(function() {
$('div, p, or span of what font size your increasing').css("font-size", function() {
return parseInt($(this).css('font-size')) + 1 + 'px';
});
});
});
使用非 px 字体大小时要小心——当字体大小为 1.142857em 时使用 Sylvain 的代码解析 int 会导致 2px!
parseInt(1.142857em) == 1
1 + 1 + 'px' == 2px
这是我如何使用 jQuery UI 滑块进行操作的示例。
这里的例子
HTML:
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="text">
<h1>Hello, increase me or decrease me!</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div id="mySlider"></div>
</div>
</div>
</div>
CSS:
.text h1 {
color: #333;
font-family: Arial, sans-serif;
font-size: 30px;
}
JS:
$("#mySlider").slider({
range: "min",
min: 30,
max: 70,
slide: function(e, u) {
$(".text h1").css("font-size", u.value + "px"); // We want to keep 30px as "default"
}
});
$(document).ready(function () {
var i = 15;
$("#myBtn").click(function () {
if (i >= 0) {
i++
var b = $("#myText").css({"background-color": "yellow", "font-size": i})
}
})
//If you want to decrease it too
$("#myBtn2").click(function () {
if (i <= 500) {
i--
var b = $("#myText").css({"background-color": "yellow", "font-size": i})
}
})
})
此解决方案使用百分比而不是使用 px,也不需要在 HTML 中设置大小或样式标题。
HTML:
<p>This is a paragraph.</p>
<button id="btn">turn up</button>
jQuery:
var size = "100%";
$("#btn").click(function() {
size = parseFloat(size)*1.1+"%";// multiplies the initial size by 1.1
$("p").css("fontSize", size);// changes the size in the CSS
});