2011-11-22 71 views
0
<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

回答

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

這個例子也不起作用 – JarM

+0

你需要改變內容,把JS放在最下面。 PS:使用jQuery更容易。現在試試。 – Cesar

+0

什麼是jQuery? – JarM

1

我看到兩個問題。

首先,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

相關問題