I'm trying to create a dyna开发者_JAVA技巧mic element, apply some css
on it from an external css
file, and access the properties with jQuery
. It works on Firefox but it does not on Chrome
.
Here is an example :
CSS file (myFile.css):
.myClass {
width : 200px;
font-family : Verdana;
font-size : 12px;
}
javascript code in a different file (myFile.js):
var title = $("<p/>").attr({id: "myId"}).addClass("myClass").appendTo(content);
var titW = title.width();
var titFSize = parseInt(title.css("fontSize"));
var titFFamily = title.css("fontFamily");
console.log(titW, titFSize, titFFamily); // Firefox returns good values, Chrome does not
Any ideas? Thanks!
Ok, I've got the answer based on your comment. You need to enclose all your jQuery code in a DOMReady event.
jQuery(document).ready(function ($) {
// jQuery code goes here
});
This ensures that the Document Object Model (DOM) will be fully ready before it runs.
The 100ms delay you mentioned in your comment isn't a good idea, because you don't know that the stylesheet will always load in 100ms.
精彩评论