如何在代码中为对象添加宽度?

时间:2011-11-22 18:39:26

标签: javascript

<script language="javascript">
var widthx = document.getElementById('testx');
var newwidth = document.getElementById('mycontent').style.width = widthx.width + 45 //not working
</script>

<style type="text/css">
#testx
{
width: 950px;
}

#mycontent
{
width: 800px; //this width needs to change from javascript to 950 + 45 px
}

....

我想将mycontent的宽度更改为testx宽度+ 45像素(px)。有谁知道如何在javascript中执行此操作?

2 个答案:

答案 0 :(得分:2)

<style type="text/css">
#testx
{
    width: 950px;
}

#mycontent
{
    width: 800px; //this width needs to change from javascript to 950 + 45 px
}
</style>

<!-- YOUR HTML HERE -->

<script language="javascript">
function onlyNumber(str) {
    str = str.toString();
    return str.replace(/\D/g, '');
}
var widthx = onlyNumber(document.getElementById('testx').style.width) * 1;
document.getElementById('mycontent').style.width = (widthx + 45) + "px";
</script>

使用jQuery:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js" type="text/javascript"></script>
<script language="javascript">
    function onlyNumber(str) {
        str = str.toString();
        return str.replace(/\D/g, '');
    }
    $(document).ready(function() {
       var widthx = onlyNumber($("#testx").css("width")) * 1;
       $("#mycontent").css("width", (widthx + 45) + "px");
    });
</script>
<style type="text/css">
#testx
{
    width: 950px;
}

#mycontent
{
    width: 800px; //this width needs to change from javascript to 950 + 45 px
}
</style>

</head>
<body>
<!-- YOUR HTML HERE -->
</body>
</html>

答案 1 :(得分:1)

我看到两个问题。

首先,widthx.width不存在。您应该使用widthx.offsetWidth

其次,简单数字不是…style.width的正确值。例如,使用widthx.offsetWidth + 45 + 'px'