如何将宽度添加到代码中的对象?
问题描述:
<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中做到这一点?如何将宽度添加到代码中的对象?
答
<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>
尝试在两个'widthx'和'widthx.width'做'console.log'或'alert' - 这将帮助你找到你的问题。 – jball
会发生什么? 'style.width'将是一个字符串,如果你想执行数学运算,你必须先将它转换为数字。 –
有趣的是,我知道,但我不知道语法 – JarM