开发者

Setting css properties with javascript not working on strict mode?

开发者 https://www.devze.com 2022-12-18 05:15 出处:网络
I\'m embarassed to admit that I can\'t find the standards-compliant method to modify CSS properties using Javascript. Or at least, I assume so, due to the following:

I'm embarassed to admit that I can't find the standards-compliant method to modify CSS properties using Javascript. Or at least, I assume so, due to the following:

The following piece of code works fine in Firefox/WebKit without a DOCTYPE declaration, but doesn't work with the doctype specified (ei开发者_开发知识库ther HTML 4 or 5):

function setWindowSize(width, height)   {
    console.log("Syncing dimensions:",width,height);            // prints correct values
    var container = document.getElementById('canvasProxy');
    console.log(container);                                     // prints valid element
    console.log(container.style);                               // prints valid object
    container.style['width'] = width;
    container.style['height'] = height;
    console.log(container.style['width'], container.style['height']); // prints empty values
}

where canvas proxy is simply defined as:

<div id="canvasProxy"></div>

and has no style associated with it. The above code does not execute until after the DOM has loaded.

style.setProperty and style.getPropertyCSSValue also fail to work. So uh...what's the correct form? Am I going crazy?

(I'm betting that jQuery could handle this just fine, but I'm trying to keep page size at an absolute minimum in this particular case.)


You don't say what values you are passing, or what you consider to be correct, but I'd give good odds that you are passing integers and not lengths.

CSS requires units on lengths other that 0. Most browsers will perform error recovery (in direct contradiction to the CSS specification) and assume you mean px if you fail to specify a unit … but only in Quirks Mode.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $('canvasProxy').css('width', 300);
    $('canvasProxy').css('height', 50);
</script>
0

精彩评论

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