JQuery功能,可在任何地方增加字体大小

JQuery function to increase the font size everywhere

本文关键字:增加 字体 方增加 功能 任何地 JQuery      更新时间:2023-09-26

我正在尝试创建一个单击函数来增加每段文本(paspanh1等)的字体大小。我不想使用这样的选择器

var allText = $('.page-container a, .page-container p, .page-container h1, .page-container h2, ...');

因为我希望这是通用的和可维护的。我的愿望能实现吗?

给定简化的 HTML,如下所示(因为您在问题中没有提供任何内容):

<button id="up">+</button><button id="down">-</button>
<h1>Heading text</h1>
<div>
    <p>A div, with</p>
    <ul>
        <li>Various elements</li>
    </ul>
     <h2>And another heading</h2>
    <aside>At this point, I'm sure that you get the point</aside>
    <blockquote>But if you don't, then I'm sure it can be explained</blockquote>
</div>

和 CSS:

/* This is more or less irrelevant, it's just to show
   that the <body> element has an explicit font-size,
   in pixels (but em would work also) */
body {
    font-size: 16px;
}
/* and all other elements have relative font-sizes,
   basing their own font-size upon the inherited
   font-size from their ancestors: */
h1 {
    font-size: 2em;
}
div {
    font-size: 1em;
}
ul {
    font-size: 1.2em;
}
h2 {
    font-size: 1.5em;
}
aside {
    font-size: 0.8em;
}
blockquote {
    float: left;
    font-size: 1.2em;
    border-left: 2px solid #f90;
    padding: 0.5em;
}

以下 jQuery 将起作用:

// binds a simple click event-handler:
$('button').on('click', function(){
    // caching the clicked element:
    var clicked = this;
    // selecting the <body> element,
    // using the css() method to set the 'font-size'
    // via the anonymous function:
    $('body').css('font-size', function (i,size) {
        // i: the index of the current element in the collection
        // size: the current value of the current element
        // using parseInt to get a number in base-ten,
        // adding either 2 (if the clicked element was #up)
        // or -2 (if the clicked element was not #up):
        // appending 'px' to the number to make it a valid
        // css unit:
        return parseInt(size,10) + (clicked.id === 'up' ? 2 : -2) + 'px';
    });
});

JS小提琴演示。

引用:

  • css() .
  • on() .
$('*').css('font-size', '15px');

可能会做这个伎俩。

此解决方案按比例放大文本。

$(document).ready(function() {
    $('.big').on('click', function() {
        $('*').each(function() {
            var fontsize = parseInt($(this).css('font-size'));
            console.log(fontsize);
            var newFontsize = (fontsize * 1.1) + 'px';
            console.log(newFontsize)
            $(this).css('font-size', newFontsize);
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="big">englarge<a/>
<p>askdjfhasjdhf</p>
<a>lkajsdlfkjasdf</a>
<h1>askjdflasf</h1>
a;sldkfalskdfsdf