javascript动态更改宽度不成功

时间:2013-03-19 15:19:30

标签: javascript

我有以下代码来更改div的高度/宽度,但它不起作用。以下警报消息仅打印空白值。请帮忙

<script>
    function showmyidlist() {
        try {
            var myid = document.getElementById('myid');
            var myidlist = document.getElementById('myidlist');
            var divinput = myid.getElementsByTagName("input")[0];
            alert(divinput.style.height + ":" + divinput.style.height);
            myid.style.width = divinput.style.width;
            myid.style.height = divinput.style.height;
            alert(myid.style.width + ":" + divinput.style.width);

            if (myidlist.style.position != 'absolute') {
                myid.appendChild(myidlist);
                myid.style.position = 'relative';
                myidlist.style.position = 'absolute';
                myidlist.style.top = '10px';
                myidlist.style.left = '0px';
                myidlist.style.zindex = 1;
                myidlist.style.display = 'block';
            } else if (myidlist.style.position == 'absolute') {
                myidlist.style.position = '';
                myidlist.style.zindex = 0;
                myidlist.style.display = 'none';
                myid.style.position = '';
            }
        } catch (e) {
            alert(e);
        }
    }
</script>


<table>
    <tr>
        <td style="padding:0px 10px 0px 0px;text-align:right;width:20%;">Name</td>
        <td style="padding:0px 0px 0px 0px;text-align:center;width:60%;">
            <div id="myid"><input type="text" name="myid" value="" onclick="showmyidlist()"></div>
        </td>
        <td style="padding:0px 0px 0px 10px;text-align:left;width:20%;">
            <input style="width:200px;" type="submit" class="button" name="submit" value="Add My Id" />
        </td>
    </tr>
</table>
<div id="myidlist" style="display:none;"></div>

1 个答案:

答案 0 :(得分:1)

尝试:

alert(divinput.clientHeight + ":" + divinput.clientWidth);

clientHeight和clientWidth属性是动态设置的,其中width和height属性通常是最初设置的值。