![](/img/trans.png)
[英]jQuery script run on (document).ready AND $(window).resize
[英]jQuery resize and on document ready combination
我有這個JS函數來從可靠的屏幕大小中刪除類。 它僅在您調整屏幕大小時才起作用(我認為這是預期的行為),但是,我也需要在加載時使用它。
require(['jquery'], function(){
jQuery(window).resize(function() {
var innerWidth = window.innerWidth;
if (innerWidth < 800) {
jQuery("#logo-container").removeClass('pull-left');
} else if (innerWidth > 800) {
jQuery("#logo-container").addClass('pull-left');
}
});
});
我用document.ready包裝了函數,並在resize事件之前添加了相同的內容。 現在有這樣的事情:
require(['jquery'], function(){
jQuery(document).ready(function() {
var innerWidth = window.innerWidth;
if (innerWidth < 800) {
jQuery("#logo-container").removeClass('pull-left');
} else if (innerWidth > 800) {
jQuery("#logo-container").addClass('pull-left');
}
jQuery(window).resize(function() {
var innerWidth = window.innerWidth;
if (innerWidth < 800) {
jQuery("#logo-container").removeClass('pull-left');
} else if (innerWidth > 800) {
jQuery("#logo-container").addClass('pull-left');
}
});
});
});
現在,我的函數的結果是我想要的,但是,我覺得我正在重復我的代碼。
這是正確的做法嗎? 有更好的替代方法嗎?
任何建議將受到高度贊賞。
避免重復代碼。
創建一個函數並在文檔就緒函數和窗口調整大小函數上調用它...
在下面的代碼中,所有代碼都轉到
OnScreenResized()
函數。
require(['jquery'], function() {
jQuery(document).ready(function() {
OnScreenResized();
});
jQuery(window).resize(function() {
OnScreenResized();
});
function OnScreenResized() {
var innerWidth = window.innerWidth;
if (innerWidth < 800) {
jQuery("#logo-container").removeClass('pull-left');
} else if (innerWidth > 800) {
jQuery("#logo-container").addClass('pull-left');
}
}
});
需要記住的是,如果您需要復制並粘貼完全相同的代碼塊,則始終是將其重構為函數調用的好時機:
require(['jquery'], function(){
jQuery(document).ready(function() {
jQuery(window).resize(function() {
toggleClass();
});
toggleClass();
});
function toggleClass() {
var innerWidth = window.innerWidth;
if (innerWidth < 800) {
jQuery("#logo-container").removeClass('pull-left');
} else if (innerWidth > 800) {
jQuery("#logo-container").addClass('pull-left');
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.