0

2つのボタンと1つのテキストを表示するコードを作成しました。ボタンをクリックすると、テキストのサイズが大きくなり、[縮小]をクリックすると、サイズが小さくなります。しかし、これはワンクリックでのみ機能します。2回クリックしても、関数は呼び出されません。なぜこうなった?これがそのコードです。

<html>
<head>
    <script type="text/javascript">
        function Grow()
        {
            var a=document.getElementById(1);
            a.style.fontSize=a.style.fontSize+50;

        }
        function Shrink()
        {
            var a=document.getElementById(1);
            a.style.fontSize=20;

        }
    </script>
</head>
<body>
    <input type="button" value="grow" onclick="Grow()">
    <input type="button" value="shrink" onclick="Shrink()">
    <p id="1"> Hello </p>
</body>

4

1 に答える 1

3

初めてgrowアクションを実行すると、null値で開始したときに、単位pxが自動的に使用されます。.fontSizeの値を解析してから、演算を実行する必要があります。これを試して...

parseInt(a.style.fontSize.replace('px', ''));

算術演算を実行できる数値を取得します。

略さずに...

function Grow()
{
    var a=document.getElementById(1);

    // Get a number we can perform arithmetic on
    size = parseInt(a.style.fontSize.replace('px',''));

    // Additional check needed because original dimensions not specified
    if (!isNaN(size)) { // If we now have a number we can use
        a.style.fontSize=size+50;
    } else { // Otherwise, set to 50 (assuming we are starting from 0px)
        a.style.fontSize=50;
    }
}
于 2012-11-15T14:04:32.203 に答える