你外面的定義它們功能。另外,因爲load
在頁面加載過程中發生得相當晚,所以您需要主動初始化它們,然後根據load
和resize
對其進行更新。這表明你想要一個可重複使用的功能:
var menuHeight; // Defining...
var contactHeight; // ...them
grabHeights(); // Proactive
$(window).on("load resize", grabHeights); // And on events
function grabHeights() {
if ($(window).width() < 768) {
menuHeight = '0px';
contactHeight = '100%';
}
else {
menuHeight = ($('#desktop-menu').height() + 'px').toString();
contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
}
}
如果你的代碼是不是已經在一個範圍的功能,你可能希望把它放在一個:
(function() {
var menuHeight;
var contactHeight;
grabHeights();
$(window).on("load resize", grabHeights);
function grabHeights() {
if ($(window).width() < 768) {
menuHeight = '0px';
contactHeight = '100%';
}
else {
menuHeight = ($('#desktop-menu').height() + 'px').toString();
contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
}
}
})();
...因爲全局是一壞事™。 :-)
你會看到別人告訴你先走一步,掛鉤事件,然後手動觸發它:
$("selector").on("event", function() {
// ...
}).triger("event");
我不是一個球迷。如果你需要調用一個函數,只需調用它。
如果你還沒有在某個地方聲明'menuHeight'和'contactHeight',那麼這個代碼就會陷入[隱式全局的恐怖](http://blog.niftysnippets.org/2008/03/horror-of- implicit-globals.html)*(這是我貧血的小博客上的一篇文章)*。一定要聲明你的變量。 :-) –