问题描述
我有功能:
function changeFontSize(points) {
var e = document.getElementsByTagName("BODY")[0];
var style = window.getComputedStyle(e);
var size = style.getPropertyValue('font-size');
size = size.replace("px", "");
size = size * 1;
size = size + points;
//if(size <= 0 && size <= 3){
e.style.fontSize = size + "px";
localStorage.setItem("size", size);
//}
}
function saveFontSize() {
var size = localStorage.getItem("size");
if (size !== null) {
var e = document.getElementsByTagName("BODY")[0];
e.style.fontSize = size + "px", '!important';
}
}
document.addEventListener("DOMContentLoaded", saveFontSize);
<a href="#" onclick="changeFontSize(1);">plus</a>
<a href="#" onclick="changeFontSize(-1);">minus</a>
上面的代码工作正常。 上述功能放大并缩小了我网站上的字体大小。
我需要将此函数的功能限制为字体大小的3倍。 字体大小减小(较小的字体大小)不能小于其原始(原始大小)。
怎么做? 请帮忙。
1楼
您可以存储初始字体大小,然后使用和 :
body.style.fontSize = Math.max(
initialBodyFontSize,
Math.min(
initialBodyFontSize * 3,
getBodyFontSize() + points
)
) + 'px';
演示(没有通过localStorage
部分加载/保存,因为这里不可能):
{ var body = document.querySelector('body'); var initialBodyFontSize; // Note: this supposes the body's font size is expressed in px function getBodyFontSize() { return parseFloat(window.getComputedStyle(body).getPropertyValue('font-size')); } function changeBodyFontSize(points) { body.style.fontSize = Math.max( initialBodyFontSize, Math.min( initialBodyFontSize * 3, getBodyFontSize() + points ) ) + 'px'; console.log(body.style.fontSize); } document.addEventListener('DOMContentLoaded', function () { initialBodyFontSize = getBodyFontSize(); }); }
<a href="#" onclick="changeBodyFontSize(1);">plus</a> <a href="#" onclick="changeBodyFontSize(-1);">minus</a>
另请注意,您通常应该避免使用onclick
和类似的属性,而是更喜欢对关联的DOM元素执行addEventListener
JS调用。