[英]jQuery loading order in Wordpress
我有一個jQuery腳本,可讀取img高度並將樣式標簽添加到head標簽。
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。 但這只是我的猜測... script標簽就在</body>
標簽之前。
有任何想法嗎?
如果要確保首先將圖像完全加載,請使用以下代碼:
/* 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");
});
});
另請參閱以下答案: 將jquery腳本延遲到其他所有內容都已加載之前
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.