Вопрос

I simply made a div and gave it height and width. Then I made a function called resetSize() from which I want to change the height and width of any element, but something's wrong! Here's my source code:-

<!DOCTYPE html>
<html>
    <head>
        <title>Get Value</title>
        <style>
            #demo{
                height:50px;
                width:50px;
                background:cyan;
            }
        </style>
    </head>

    <body>
        <div id="demo"></div>
    </body>

    <script>
        function resetSize(elementId, height, width){
            var el = document.getElementById(elementId);
            el.style.height = height;
            el.style.width = width;
        }
        resetSize('demo', 500, 500);
    </script>

</html>
Это было полезно?

Решение 2

You need to add units, like px.

function resetSize(elementId, height, width){
    var el = document.getElementById(elementId);
    el.style.height = height + "px";
    el.style.width = width + "px";
}

The above way is hardcoded to "px". You could pass the unit instead.

function resetSize(elementId, height, width, unit){
    var el = document.getElementById(elementId);
    el.style.height = height + (unit || "px");
    el.style.width = width + (unit || "px");
}

resetSize('demo', 500, 500, "px");

Or just include it directly in the value, and use the original function.

resetSize('demo', "500px", "500px");

Другие советы

The thing you missing is px - the unit

function resetSize(elementId, height, width) {
    var el = document.getElementById(elementId);
    el.style.height = height + 'px';
    el.style.width = width + 'px';
}

Demo

You forgot to set the px. See http://jsfiddle.net/X5B4r/ for a working example.

Your height & width need to be set as strings with the 'px' unit notation:

<!DOCTYPE html>
<html>
    <head>
        <title>Get Value</title>
        <style>
            #demo{
                height:50px;
                width:50px;
                background:cyan;
            }
        </style>
    </head>

    <body>
        <div id="demo"></div>
    </body>

    <script>
        function resetSize(elementId, height, width) {
            var el = document.getElementById(elementId);
            el.style.height = height;
            el.style.width = width;
        }
        resetSize('demo', '500px', '500px');
    </script>

</html>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top