Javascript 我可以为style.top指定离轴吗?

Javascript 我可以为style.top指定离轴吗?,javascript,css,Javascript,Css,在javascript中,我可以这样分配: var tempHeight = document.getElementById("header").offsetHeight; document.getElementById("content").style.top = tempHeight; 运行上述脚本后,div“content”是否具有“top”propery=tempHeight? 我试过了,但没用,有什么建议吗? 谢谢 CSS属性需要一个单位和值。添加px应该可以: document.g

在javascript中,我可以这样分配:

var tempHeight = document.getElementById("header").offsetHeight;
document.getElementById("content").style.top = tempHeight;
运行上述脚本后,div“content”是否具有“top”propery=tempHeight? 我试过了,但没用,有什么建议吗?
谢谢

CSS属性需要一个单位和值。添加
px
应该可以:

document.getElementById("content").style.top = tempHeight + "px";

top
CSS属性需要一个单位和值。添加
px
应该可以:

document.getElementById("content").style.top = tempHeight + "px";
你只需要一个单位

document.getElementById("content").style.top = String(tempHeight) + "px";
你只需要一个单位

document.getElementById("content").style.top = String(tempHeight) + "px";

您必须将
+'px'
或某些单位添加到
style.top
语句的末尾

此外,
#内容
必须设置
位置
样式

CSS

JS


您必须将
+'px'
或某些单位添加到
style.top
语句的末尾

此外,
#内容
必须设置
位置
样式

CSS

JS


非常感谢您,我是Javascript新手,我尝试了一些链接tempHeight.toString的方法,但没有成功。感谢您的String()函数:DA
Number
String
关联时会自动转换为
String
。因此,强制转换
String
是不必要的。
console.log(typeof tempHeight)//number
console.log(typeof(tempHeight+'px'))//String@Trevor你是对的-总是显式地强制转换到String只是我的一个老习惯。但你是对的,在这种情况下完全没有必要。非常感谢你,我对Javascript还不熟悉,我尝试了一些链接tempHeight.toString的方法,但没有成功。感谢您的String()函数:DA
Number
String
关联时会自动转换为
String
。因此,强制转换
String
是不必要的。
console.log(typeof tempHeight)//number
console.log(typeof(tempHeight+'px'))//String@Trevor你是对的-总是显式地强制转换到String只是我的一个老习惯。但你是对的,在这种情况下完全没有必要