JQuery函数可以增加字体大小

时间:2015-01-28 16:41:50

标签: javascript jquery

我尝试制作点击功能,增加每段文字的字体大小(paspanh1等)。我不想使用像

这样的选择器
var allText = $('.page-container a, .page-container p, .page-container h1, .page-container h2, ...');

因为我希望这是一般的和可维护的。我的愿望可以被授予吗?

3 个答案:

答案 0 :(得分:2)

给出简化的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 Fiddle demo

参考文献:

答案 1 :(得分:0)

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

可能会做到这一点。

答案 2 :(得分:0)

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

$(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