如何使用jQuery使字体大小在我们调整窗口大小时扩大

如何使用jQuery使字体大小在我们调整窗口大小时扩大

在这篇文章中,我们将学习如何使用jQuery来增加或减少HTML中元素的字体大小,当窗口被调整时。这可以用在字体大小必须根据浏览器窗口的宽度进行响应的情况下。

方法:我们将使用jQuery的css()、width()和resize()方法。由于字体大小必须根据窗口大小的调整而改变,resize()方法可以应用于窗口对象。现在,必须在这个resize()方法中定义一个回调函数。在这个函数中,我们将使用$(*)选择器选择HTML文档中的所有元素。然后,我们将使用css()方法修改font-size属性,并使font-size相对于窗口宽度的一个百分比(像素)。当窗口大小调整时,这个函数将被重复执行。

例子:在这个例子中,所有元素的字体大小都按照窗口宽度的8%来调整。

<!DOCTYPE html>
<html>
  
<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
    </script>
  
    <!-- Basic inline styling -->
    <style>
        body {
            text-align: center;
        }
  
        h1 {
            color: green;
            font-size: 25px;
        }
  
        p {
            font-weight: bold;
            font-size: 25px;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
  
    <p>
        Notice the scaling in font size
        as the window is resized
    </p>
  
    <script type="text/javascript">
        (window).resize(function () {
              
            // Calculate the final font size 
            // to be 8% of the window width
            let size =(window).width() * 0.08;
  
            // Use the css() method to set the
            // font-size to all the elements on
            // the page
            $("*").css("font-size", size + "px");
        });
    </script>
</body>
  
</html>
HTML

输出:

如何使用jQuery使字体大小在我们调整窗口大小时扩大?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册