开发者

Javascript attributes compact

Is there a way to assign attributes in a mor开发者_开发知识库e compact manner I dont really want to use setAttribute as it seems to be buggy in ie8 This list is for all attributes so its quite long

else if(a=="textalign")
{
    e.style.textAlign="";
    e.align=v
}


if(a=="textalign")
{
    e.style.textAlign="";
    e.align=v
}

I don't know why you are trying to set alignment via an HTML attribute rather than just using the CSS... this is much less reliable as there are many elements which have no align attribute. HTML align is also deprecated and should be avoided in general.

You don't say what the “other attributes” are that you might want to set. If you are talking specifically about HTML attribute properties it's easy to set them by a name in a string:

e[a]= v;

But then you need a to be the HTML attribute property name, which would be ‘align’ not ‘textalign’. It wouldn't do anything special to try to workaround CSS overrides like textAlign, because there is no automated way to do that, and the interaction between the deprecated HTML styling attributes and CSS is ill-defined. Stick to attributes or CSS (CSS is highly preferable); don't use both.

If you are talking about setting any CSS style property, as I might guess from the name being ‘textalign’, that's done similarly:

e.style[a]= v;

But then, again, you'd want to be using the exact style property name ‘textAlign’ not ‘textalign’.

If you want to set CSS style properties by their CSS name, like ‘text-align’, you could transform that to the DOM name automatically:

// convert foo-bar-baz to fooBarBaz
//
var doma= a.replace(/-([a-z])/g, function(m, g) {
    return g.toUpperCase();
});

e.style[a]= v;

If you really do need to use case-lossy names like ‘textalign’ you'd have to use a lookup of all property names you wanted to use to get the case back:

var propernames= ['textAlign', 'borderColor', 'paddingTop']; // etc

for (var i= propernames.length; i-->0;)
    if (propernames[i].toLowerCase()===a)
        a= propernames[i];

e.style[a]= v;

Forget setAttribute. It has nothing to do with style properties (it's a bug in IE6-7 that it even works on styles there), and you shouldn't use it on elements either for HTML documents, as there are other IE6-7 bugs to contend with there. Stick to the ‘DOM Level 2 HTML’ direct property access stuff, which is more reliable and easier to read.


Use a class instead of giving all the attribute values.

.testClass 
{
   // set all attribute values here
}

e.className = "test";

See

element.className


Use some framework such as JQuery, it takes care of all of your browser incompatibility issues. In JQuery you use the .css('attributeName', 'value')method.


jQuery would make that easy with .attr({attr1: val, attr2: val}) etc. It would also shield you from many cross-browser compatibility bugs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜