gpt4 book ai didi

jquery - 单击时增加整个元素的字体大小

转载 作者:太空宇宙 更新时间:2023-11-04 03:54:27 24 4
gpt4 key购买 nike

我正在为主要面向老年人的客户设计 Web 应用程序。他们想要一个功能,点击一个按钮,整个元素的字体大小就会增加/减少。

这样做的最佳方法是什么?我能想出的唯一解决方案是,为每个页面提供切换按钮,然后使用 jquery 执行类似

的操作
...
$('body').css('font-size', '20px');
...

我不确定这是否是一种优雅的方法,因为各种 p, h1, h2... 都分配了不同的字体大小,而且这将涉及对每个页面的点击,而不是比一般的一次点击。

最佳答案

很简单,在所有从 body 派生的元素上使用相对字体大小 - 这是所有上下文元素。

body{
font-size: 20px; /*This is our default*/
}

h1{
font-size: 1em; /*Relative to the body, this will also be 20px*/
}

h2{
font-size:0.8em; /*This will be 20 * 0.8 = 16px;*/
}

h3{
font-size:80%; /*This is the same thing as above - 20 * 80% = 16px; */
}

h1.huge{
font-size:1.2em; /*This one will be 20 * 1.2 = 24px */
}

现在我们已经做好了准备。所有元素都有基于 body 的相对字体大小。现在,调整每个元素的字体大小所需要做的就是通过单击调整 body 元素的字体大小:

var button = document.getElementById('.myButton');
button.addEventListener('click', function(){
var body = document.querySelector('body');
body.style.fontSize = '25px';
});

(您也可以想象并在 localStorage 中跟踪此按钮的点击,或者只是一个 cookie 以跨页面记住此选择)

现在我们的尺寸将像这样解决:

h1{
font-size: 1em; /*25px*/
}

h2{
font-size:0.8em; /*This will be 25 * 0.8 = 20px;*/
}

h3{
font-size:80%; /*This is the same thing as above - 24 * 80% = 20px; */
}

h1.huge{
font-size:1.2em; /*This one will be 25 * 1.2 = 30px */
}

注意:相对字体大小实际上是根据父元素计算的,不一定是body。这意味着如果您为某个元素定义了相对字体大小,而该元素的父元素具有相对字体大小,则您需要做一些数学运算:

body{
font-size:25px;
}

div.container{
font-size: 0.8em; /* 20px if a child of body */
}

div.container > p{
font-size:0.8em; /* 25px * 0.8 * 0.8 = 16px; */
}

关于jquery - 单击时增加整个元素的字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22987266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com