0

我想在调用时使用 javascript 函数从 div 中减去 50px。为什么这不起作用?

<!DOCTYPE html>
<html>
<head>
<script>
        function resizeDiv(id)
        {
            obj.style.height = ( parseFloat( obj.style.height ) - 50 ) + 'px';
        }
        </script>

<style type="text/css">
            #divId{
            background:blue;
            width:300px;
            height:100px;

</style>
</head>
<body>
    <button onclick="resizeDiv('divId')">Try it</button>   
    <div id="divId"></div>
</body>
</html>
4

1 回答 1

0

您没有为高度定义 obj 或样式属性,并且错过了 css 中的括号:

<!DOCTYPE html>
<html>
<head>
<script>
function resizeDiv(id){
   var obj=document.getElementById(id);
    if(obj){
        obj.style.height= (obj.offsetHeight- 50)+ 'px';
    }
}
</script>
<style type= "text/css">
#divId{
    background:blue;
    width:300px;
    height:100px;
}
</style>

</head>
<body>
    <button onclick="resizeDiv('divId')">Try it</button>   
    <div id="divId"></div>
</body>
</html>
于 2013-02-15T05:12:19.640 回答