简体   繁体   中英

javascript onclick function to enlarge text

I'm not sure why, but I can't seem to get this to work.

Here is my function to enlarge my font.

<script type="text/javascript">
    function growText() {
        var text = document.getElementById("t_left_text");
        text.font-size=22px;        
</script>

And here is where I call it

<div id="t_left" onclick="growText()">
    <br />
    <p id="t_left_text">Mountains are beautiful land structures <br /> that are a result of plate tectonics.</p>
    <br />
</div>

Try:

text.style.fontSize = "22px";

DEMO: http://jsfiddle.net/C2MWN/

When you want to change an element's CSS, you need to use the style property. To determine the name of the specific style property, the CSS name is converted to camel case - "font-size" becomes "fontSize", so that the identifier is valid in JavaScript.

While setting the style properties definitely works, and although this is a very simple example, it might be easier to deal with adding and removing a class . This is especially useful when setting multiple CSS properties. The class could be defined as:

.enlarged-font {
    font-size: 22px;
}

And you would manipulate the text.className property (and/or the classList property).

Depending on the browser you're using, you could have easily provided a better description (as obvious as it was for some of us) of the problem by using the JavaScript console in the browser. In Firefox, you could use Firebug. In Internet Explorer and Chrome, you could use Developer Tools. If installed/enabled, these can usually be brought up by pressing the F12 on your keyboard.

Also, don't forget to close your function with a } .

Reference:

Use below code

function growText() {
            var text = document.getElementById("t_left_text");
            text.style.fontSize ="22px";
}

Working example http://jsfiddle.net/D2anZ/

Here's a version that uses CSS to accomplish what you want. That way if you want to do this to different sets of text at the same time, and want to change that font size, there's only one place you need to make the change. (Or if you also want to add other css properties (color, etc.)

Fiddle

JavaScript

function growText() {
    var text = document.getElementById("t_left_text");
    text.className = 'large-font';
}

CSS

.large-font {
    font-size: 22px;
}

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