如何创建一个函数来设置或获取样式属性值

how to create a function to set or get style property value?

本文关键字:获取 设置 样式 属性 一个 何创建 创建 函数      更新时间:2023-09-26

我编写了一个函数,想要设置或获取样式属性值:

function $(ID){return document.getElementById(ID);}
Object.prototype.css=function(style,value){
    if(value==undefined){
        return eval("this.style."+style);
    }
    else{
        if(isNaN(value)){
            return eval("this.style."+style+"='""+value+"'"");
        }
        else{
            return eval("this.style."+style+"="+value);
        }
    }
}
function ad(){
    $("ad_ol").css("top","-170px");
}

它可以在FireFox、Chrome和IE9中正常工作,但不能在IE7和IE8中工作,错误消息是:Object不支持"css"属性或方法

谁能帮我?是"这个"问题吗?是有更好的功能可以做到这一点吗?

不需要eval,而且代码中还有其他缺陷
尝试使用以下内容:

function css(prop,value){
  value = value || '';
  if(prop) {
    this.style[prop] = value;
    return this.style[prop];
  }
  return true;
}
function $(ID){
  var element = document.getElementById(ID || 'nodId');
  if(element) {
    element.css = css; // create css method for this element
  }
  return element; // Note: element is null if no ID was provided
}
$("ad_ol").css("top","-170px"); //=> should work now