2016-02-02 106 views
1

我有一个jQuery脚本,它读取img高度并将样式标记添加到头标记。在Wordpress中的jQuery加载顺序

jQuery的

var img = document.getElementById('logomini'); 
height = img.clientHeight; 

$(function(){ 
    $("<style type='text/css' id='style1'>#menu ul { line-height: "+ height +"px }</style>").appendTo("head"); 
}); 

问题:有时脚本正常工作,有时不是。当我刷新我的网站(Wordpress)时,行高为80px或0px。我认为这是脚本加载的问题。当脚本加载速度比img更快时,显示0px。但这只是我的猜测......脚本标签正好在</body>标签之前。

my demo page

任何想法?

+0

图像前要设置高度可变的,你”重新获得高度,被加载。您应该在文档就绪功能中定义变量。 – APAD1

+0

那么,仍然不工作 – user4011723

回答

2

如果你想确保图像满载,然后再使用此代码:

/* In WordPress, $ may be used for other libraries, so use this safer "document ready" method */ 
jQuery(function($) { 
    /* wait until everything in the window has loaded */ 
    $(window).load(function() { 
     var img = document.getElementById('logomini'); 
     height = img.clientHeight; 
     // The above two lines could be simplified like so: 
     var height = $('#logomini').height(); 
     $("<style type='text/css' id='style1'>#menu ul { line-height: "+ height +"px }</style>").appendTo("head"); 
    }); 
}); 

也看到这样的回答:Delaying a jquery script until everything else has loaded

+0

不工作...即使当我使用文档准备功能 – user4011723

+0

对不起:)没有什么改变。尽管如此,有时候工作正常,有时候并非如此。 – user4011723

+0

现在好了:)非常感谢。 – user4011723