如何将宽度添加到代码中的对象?

问题描述:

<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中做到这一点?如何将宽度添加到代码中的对象?

+0

尝试在两个'widthx'和'widthx.width'做'console.log'或'alert' - 这将帮助你找到你的问题。 – jball

+1

会发生什么? 'style.width'将是一个字符串,如果你想执行数学运算,你必须先将它转换为数字。 –

+0

有趣的是,我知道,但我不知道语法 – JarM

<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> 
+0

这个例子也不起作用 – JarM

+0

你需要改变内容,把JS放在最下面。 PS:使用jQuery更容易。现在试试。 – Cesar

+0

什么是jQuery? – JarM

我看到两个问题。

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

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

+0

不知道你想说什么,给我举一个例子 – JarM

+0

@JarM,最后一句提供了一个直接的例子(尽管它保留了invalud'widthx.width'调用)。 – jball

+0

你可以给我写下3个单词后面的内容:getElementById('mycontent')。style.width = – JarM