问题
S/O!
I need a reliable way to detect if $(window).on('resize')
has been fired by user interaction or by a jQuery .trigger
call.
I've tried the following, but I don't seem to get the parameters back in the function call:
$(window).trigger('resize',[true]);
function prepareOnResize(e, triggered){ console.dir(triggered); }
$(window).on('resize',prepareOnResize);
Triggered seems to return the width of the screen, so I tried the following, also to no avail:
$(window).trigger('resize',[true]);
function prepareOnResize(e, width, height, triggered){ console.dir(triggered); }
$(window).on('resize',prepareOnResize);
In that instance triggered comes back undefined
.
I'm at a loss here -- any help would be greatly appreciated. Thanks!
回答1:
jQuery puts a property isTrigger
in the event object, which you can test:
function prepareOnResize(e){
if (e.isTrigger) {
console.log('resize via jQuery trigger');
} else {
console.log('resize by user');
}
}
Alternatively you can use e.originalEvent
, which jQuery only the native event object has, as mentioned here:
function prepareOnResize(e){
if (!e.originalEvent)
console.log('resize via jQuery trigger');
} else {
console.log('resize by user');
}
}
回答2:
You could try the following;
Javascript... on dom ready...
var $window = $(window);
$window.on('resize', function(event, param1) {
console.log("Window resized event triggered by...");
if (typeof param1 === 'undefined') // could also do if(param1) to test for false
console.log("System Event");
else
console.log("User Event");
// Another way to check is to check the originalEvent property
// if (e.originalEvent === undefined) alert ('triggered by code');
// else alert ('triggered by system');
});
setTimeout(function() {
$window.trigger("resize", ["Custom"]);
}, 2000);
This is more or less what you were trying in your code, and it will distinguish the 2 types of events.
I also made a jsFiddle so you can see: https://jsfiddle.net/sysdevcode/4w3b8e14/
To make it work on your code
$(window).trigger('resize',[true]);
function prepareOnResize(e, width, height, triggered){ console.dir(triggered); }
$(window).on('resize',prepareOnResize);
You need to change the order of the params on the prepareOnResize()
function,
as $(window).trigger('resize',[true]);
equates to the [true] being sent as the "width" param in your function. you wold need to do, for instance:
var $window = $(window);
$window.trigger('resize',[ $window.width(), $window.height(), true ]);
then
function prepareOnResize(e, width, height, triggered){ ... }
will work, but if you don't need to pass any params, then the e.isTrigger
of the code above is probably a bit more elegent.
来源:https://stackoverflow.com/questions/36777631/passing-parameters-to-window-onresize-when-using-triggerresize