JavaScript:如何允许用户更改网页的字体大小?
在本文中,我们将探讨创建一个函数,该函数允许用户更改整个网页的字体大小。我们通常可以在一些政府网站的右上角看到此类功能。这主要是为了方便网站用户根据需要放大网页内容。
在本文中,我们将使用JavaScript和JQuery应用相同的函数。
示例 #1
在下面的示例中,我们创建了一个简单的div程序并创建了两个按钮,即“增大”和“减小”。我们使用这两个函数来增大div的字体,并使用“减小”按钮来减小div的字体。
#文件名:index.html
<!DOCTYPE html> <html lang="en"> <head> <title>Change Font Size</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> </head> <body> <center> <h1 style="color: green"> Welcome To Tutorials Point </h1> <button type="button" value="increase" class="increaseFont"> Increase Font ++ </button> <button type="button" value="decrease" class="decreaseFont"> Decrease Font -- </button> <div style="padding: 20px; margin: 50px; font-size: 20px; border: 5px solid red;" id="container" class="data"> Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more. </div> </center> <script type="text/javascript"> $(document).ready(function(){ $(".increaseFont,.decreaseFont").click(function(){ var type= $(this).val(); var curFontSize = $('.data').css('font-size'); if(type=='increase'){ $('.data').css('font-size', parseInt(curFontSize)+1); } else{ $('.data').css('font-size', parseInt(curFontSize)-1); } // alert($('.data').css('font-size')); }); }); </script> </body> </html>
输出
要增大字体大小,请单击“增大字体 ++”按钮;要减小字体大小,请单击“减小字体 --”按钮。
广告