我有这个 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 包装了函数,并在调整大小事件之前添加了相同的内容。现在有这样的东西:
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');
}
});
});
});
现在,我的函数的结果是我想要的,但是,我觉得我在重复我的代码。
这是正确的做法吗?有没有更好的替代方法?
如有任何建议,我们将不胜感激。
最佳答案
避免重复代码。
创建一个函数并在文档就绪函数和窗口调整大小函数上调用它...
In the below code, all the code goes to
OnScreenResized()
function.
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');
}
}
});
关于javascript - jQuery 调整大小和文档就绪组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51873259/