简体   繁体   中英

Decreasing Font Size If Text Is Too Long

I want to change the font size to 36px if my h1 has more than two words and keep it as is if not.

This is my code:

window.addEvent('domready',function() {
    
        var $quote = ('#header .col-sm-12 h1');
    
        var $numWords = $quote.get('text').split(' ').length; 
    
        if (2 < $numWords) {
                $quote.setStyle('font-size','36px'); }
});

However, it doesn't work. What's wrong with it?

The site in question is 6wo.de

Please note: Changing the size via CSS by using the viewport unit is not an option in this case.

First of all it's not addEvent but addEventListener . Then you probably mean DOMContentLoaded , because domready is not an event.

To make the title smaller give an id or class to identify it easier in JavaScript.

<h1 id="page-title">My page title</h1>

Now you can make the title smaller like this.

window.addEventListener('DOMContentLoaded', function() {
    const title = $('#page-title');

    var numWords = title.text().split(' ').length; 

    if (numWords > 2) {
        title.css('font-size', '36px');
    }
});

UPDATE

If you don't want to give an id to the title for some reason, you can do like this.

window.addEventListener('DOMContentLoaded', function() {
    const title = $('#header .bottom-header h1');

    var numWords = title.text().split(' ').length; 

    if (numWords > 2) {
        title.css('font-size', '36px');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM