我知道我可以通过JavaScript 设置 CSS值,例如:
document.getElementById('image_1').style.top = '100px';
Run Code Online (Sandbox Code Playgroud)
但是,我可以获得当前特定的样式值吗?我已经阅读了我可以获得元素的整个样式的地方,但是如果我不需要,我不想要解析整个字符串.
为什么this.style[property]得到一个空字符串?我的代码是:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style type="text/css">
#test{
height:100px;
}
.tclass{
width:100px;
}
</style>
<script type="text/javascript">
function $(ID){
var element=document.getElementById(ID||'nodId');
if(element){
element.css=css;
}
return element;
}
function css(prop,value){
if(value==null){
return this.style[prop];
}
if(prop){
this.style[prop]=value;
}
return true;
}
window.onload=function(){
var element=$("test");
alert(element.css("height")+","+element.css("width")+","+element.css("background"));
//alert ,,#ccc
};
</script>
</head>
<body>
<div id="test" style="background:#CCC;" class="tclass">Test</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这段代码提醒,,#ccc,但我想知道100px,100px,#ccc,我怎么了?谁能帮我?
更新
我改变了css功能,现在它可以正常工作:
function css(prop,value){
if(value==null){
var b = (window.navigator.userAgent).toLowerCase();
var s;
if(/msie|opera/.test(b)){
s = this.currentStyle
}else if(/gecko/.test(b)){
s …Run Code Online (Sandbox Code Playgroud)