使用JavaScript更改点击时的文字大小

This post was authored by Eric Wendelin. To learn more about Eric, click here.

该帖子由Eric Wendelin撰写。 要了解有关Eric的更多信息, 请单击此处

A lot of blogs and websites that have a wide range of users tend to have buttons or images that change the text size for easier readability. This can easily be implemented with a bit of JavaScript and some HTML to attach it to. There are libraries out there that do this, but in many cases it is likely overkill. Simplicity is generally better where possible.

许多拥有广泛用户的博客和网站都倾向于使用按钮或图像来更改文本大小,以便于阅读。 只需使用一些JavaScript和一些HTML即可轻松实现。 那里有执行此操作的库,但是在许多情况下,这可能会过分杀伤力。 在可能的情况下,简单性通常会更好。

调整文本大小JavaScript函数 (The Text-Resizing JavaScript Function)


function resizeText(multiplier) {
  if (document.body.style.fontSize == "") {
    document.body.style.fontSize = "1.0em";
  }
  document.body.style.fontSize = parseFloat(document.body.style.fontSize) + (multiplier * 0.2) + "em";
}

Note that line 2 in the code above requires that you specify font-size on the <html> element (it is OK to have a font-size that is specified in pixels). Alright let's see our options for using the resizeText() function.

请注意,上面代码中的第2行要求您在<html>元素上指定字体大小(可以使用以像素为单位指定的字体大小是可以的)。 好吧,让我们看看使用resizeText()函数的选项。

HTML(我在这里使用图像,但是您可以使用任何HTML元素) (The HTML (I use images here but you can use any HTML element))


<img id="plustext" alt="Increase text size" src="images/makeTextBigger.jpg" onclick="resizeText(1)" />
<img id="minustext" alt="Decrease text size" src="images/makeTextSmaller.jpg" onclick="resizeText(-1)" />

You can of course unobtrusively add the events like this:

您当然可以毫不干扰地添加如下事件:

使用JavaScript的轻松方式 (The Unobtrusive Way Using JavaScript)


$("plustext").addEvent("click", function() {resizeText(1);});
$("minustext").addEvent("click", function() {resizeText(-1);});

Here's a simple example of this all put together. This works flawlessly on at least IE, Firefox, Opera, and Safari (others not fully tested, please give feedback :)

这是所有这些放在一起的简单示例 。 至少在IE,Firefox,Opera和Safari上,它都可以完美运行(其他未经过全面测试的用户,请提供反馈信息:)

I'm sure you readers can think of some improvements so let's see some in the comments!

我相信您的读者会想到一些改进,所以让我们在评论中看看吧!

关于埃里克·温德林 (About Eric Wendelin)

Eric Wendelin is a software engineer for Sun Microsystems. When he's not doing super-secret programming for Sun, he plays indoor soccer, playing Wii with his friends, and cheering on the Colorado Avalanche. He also writes a blog on JavaScript, CSS, Java, and Productivity at eriwen.com

Eric Wendelin是Sun Microsystems的软件工程师。 当他不为Sun做超级秘密编程时,他会踢室内足球,和他的朋友一起玩Wii,并为科罗拉多雪崩队加油。 他还在eriwen.com上撰写了有关JavaScript,CSS,Java和Productivity的博客。

翻译自: https://davidwalsh.name/change-text-size-onclick-with-javascript

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值