本文介绍了是否可以以编程方式捕获浏览器中页面上的所有事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 首先,以下是W3C标准定义的事件类型列表。 (这个列表是基于HTML5标准中定义的一个属性,我假设有几十个其他的事件类型,但这个列表的长度足够了。) abort afterprint beforeprint beforeunload blur canplay canplaythrough 更改 点击 上下文菜单 复制 cuechange cut dblclick DOMContentLoaded 拖动 拖动 dragenter dragleave dragover dragstart drop durationchange 清空 li> 错误 焦点 focusin focusout formchange forminput hashchange 输入 无效 keydown keypress keyup 加载 loadeddata loadedmetadata loadstart 消息 mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup mousewheel 离线 在线 pagehide pageshow 粘贴 暂停 玩 演奏 popstate 进度 readystatechange 重做 重置 resize 滚动 寻求 寻求 选择 显示 停止 存储 提交 暂停 timeupdate 撤消 卸载 volumechange 等待 现在,可以定义一个全局事件处理程序,当任何事件最初发生在页面上的任何元素时调用? (在这种情况下,我不想计算元素中发生的事件,因为它们从后代元素冒泡 - 这就是为什么我写的原来发生。) 如果不可能,是否至少可以定义一个事件处理程序,当任何事件冒泡到DOM树的根(即$ code >文档对象或窗口对象 - 都应该工作)? (我知道可以通过编程方式停止冒泡,但是我将在任何其他元素上没有定义其他处理程序的页面上使用此事件处理程序。)(另外,我认为有些事件不会起泡,但是我们忽略这些我知道我可以这样做(使用jQuery): $(document).bind('abort afterprint beforeprint beforeunload etc.',function(){ // handle event }); 但这对我而言是一个非常不寻常的解决方案。 btw我不需要跨浏览器解决方案。如果它只在一个浏览器中工作,我很好。 另外, Firebug能够记录事件,但我希望能够以编程方式(通过JavaScript)捕获事件,而不用让它们简单地登录到控制台中。 / p> 解决方案 / * 函数getAllEventTypes(){ if(location.href!='https://developer.mozilla.org/en-US/docs/Web/Events')return; var types = {}; $('。standard-table:eq(0)tr')。find('td:eq(1)')map(function(){ var type = $ .trim .innerText)||'OtherEvent'; types [type] = types [type] || []; var event = $ .trim(this.previousElementSibling.innerText); if (event)types [type] .push(event); }); for(var t in types)types [t] = types [t] .join(''); 返回var DOMEvents =+ JSON.stringify(types,null,4).replace(/(\w +)\:/ ig,'$ 1:'); } * / var DOMEvents = { UIEvent:abort DOMActivate错误加载大小滚动选择卸载, ProgressEvent: abort error load loadend loadstart progress progress timeout,事件:abort afterprint beforeprint缓存canplay canplay通过更改chargechange充电时间更改检查关闭放电时间更改DOMContentLoaded下载持续时间更改清空结束错误错误错误错误fullscreenchange fullscreenerror输入无效语言交换levelchange loadeddata loadedmetadata noupdate已过时离线在线打开方向转换暂停指针锁更改指针锁定​​错误播放速率更改readystatechange重置请求停止提交成功挂起时间更新updateready可见性更改volumechange等待, AnimationEvent:animationend animationiteration animationstart, AudioProcessingEvent:audioprocess, BeforeUnloadEvent:beforeunload, TimeEvent:beginEvent endEvent repea tEvent, OtherEvent:blocked complete upgradeeneeded versionchange, FocusEvent:blur DOMFocusIn未实现的DOMFocusOut未实现的focus focusin focusout, MouseEvent:click contextmenu dblclick mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup显示, SensorEvent:compassneedscalibration未实现的用户邻近, OfflineAudioCompletionEvent:complete, CompositionEvent:compositionend compositionstart compositionupdate, ClipboardEvent:copy cut paste, DeviceLightEvent:devicelight, DeviceMotionEvent:devicemotion, DeviceOrientationEvent:deviceorientation, DeviceProximityEvent:deviceproximity, MutationNameEvent:DOMAttributeNameChanged DOMElementNameChanged MutationEvent:DOMAttrModified DOMCharacterDataModified DOMNodeInserted DOMNodeInsertedIntoDocument DOMNodeRemoved DOMNodeRemovedFromDocument DOMSubtreeModified, DragEvent:drag dragend dragenter dragleave drag超过dragstart drop, GamepadEvent:gamepadconnected gamepaddisconnected, HashChangeEvent:hashchange, KeyboardEvent:keydown keypress keyup, MessageEvent:message message message message , PageTransitionEvent:pagehide pageshow, PopStateEvent:popstate, StorageEvent:storage, SVGEvent:SVGAbort SVGError SVGLoad SVGResize SVGScroll SVGUnload, SVGZoomEvent:SVGZoom, TouchEvent:touchcancel touchend touchenter touchleave touchmove touchstart, TransitionEvent:transitionend, WheelEvent:wheel} var RecentLoggedDOMEventTypes = {}; (DOMEvents中的DOMEvent){ var DOMEventTypes = DOMEvents [DOMEvent] .split(''); DOMEventTypes.filter(function(DOMEventType){ var DOMEventCategory = DOMEvent +''+ DOMEventType; document.addEventListener(DOMEventType,function(e){ if(RecentLoggedDOMEventTypes [DOMEventCategory])return; RecentLoggedDOMEventTypes [DOMEventCategory] ​​= true; setTimeout(function(){RecentLoggedDOMEventTypes [DOMEventCategory] ​​= false},5000); var isActive = e。 target == document.activeElement; if(isActive){ console.info(DOMEventCategory,'target =',e.target,'active =',document。 activeElement,'isActive =',true); } else { console.log(DOMEventCategory,'target =',e.target,'active =',document.activeElement,'isActive =',false); } },true); }); } First of all, here is a list of event types that are defined by the W3C standards. (This list is based on the onevent attributes defined in the HTML5 standard. I assume that there are dozens of other event types, but this list is long enough as it is.) abortafterprintbeforeprintbeforeunloadblurcanplaycanplaythroughchangeclickcontextmenucopycuechangecutdblclickDOMContentLoadeddragdragenddragenterdragleavedragoverdragstartdropdurationchangeemptiedendederrorfocusfocusinfocusoutformchangeforminputhashchangeinputinvalidkeydownkeypresskeyuploadloadeddataloadedmetadataloadstartmessagemousedownmouseentermouseleavemousemovemouseoutmouseovermouseupmousewheelofflineonlinepagehidepageshowpastepauseplayplayingpopstateprogressratechangereadystatechangeredoresetresizescrollseekedseekingselectshowstalledstoragesubmitsuspendtimeupdateundounloadvolumechangewaitingNow, is it possible to define a global event handler that is called when any event originally occurs on any element on the page? (In this case, I don't want to count those events that occurred on elements because they bubbled up from a descendant element - that's why I wrote "originally occurs".)If that is not possible, is it at least possible to define an event handler that is called when any event bubbles up to the root of the DOM tree (which is either the document object or the window object - both should work)? (I know that it's possible to stop bubbling programmatically, but I would use this event handler on a page that has no other handlers defined on any other elements.) (Also, I believe some events don't bubble up, but let's ignore these cases for the sake of this argument.)I know that I can do this (using jQuery): $(document).bind('abort afterprint beforeprint beforeunload etc.', function() { // handle event});but that would be a rather undesirable solution for me.btw I don't need a cross-browser solution. If it works in just one browser, I'm fine.Also, Firebug is able to log events, but I would like to be able to catch the event programmatically (via JavaScript) rather then having them simply logged in the console. 解决方案 /*function getAllEventTypes(){ if(location.href !='https://developer.mozilla.org/en-US/docs/Web/Events') return; var types = {}; $('.standard-table:eq(0) tr').find('td:eq(1)').map(function(){ var type = $.trim(this.innerText) || 'OtherEvent'; types[type] = types[type] || []; var event = $.trim(this.previousElementSibling.innerText); if(event) types[type].push(event); }); for(var t in types) types[t] = types[t].join(' '); return "var DOMEvents = "+JSON.stringify(types, null, 4).replace(/"(\w+)\":/ig, '$1:');}*/var DOMEvents = {UIEvent: "abort DOMActivate error load resize scroll select unload",ProgressEvent: "abort error load loadend loadstart progress progress timeout",Event: "abort afterprint beforeprint cached canplay canplaythrough change chargingchange chargingtimechange checking close dischargingtimechange DOMContentLoaded downloading durationchange emptied ended ended error error error error fullscreenchange fullscreenerror input invalid languagechange levelchange loadeddata loadedmetadata noupdate obsolete offline online open open orientationchange pause pointerlockchange pointerlockerror play playing ratechange readystatechange reset seeked seeking stalled submit success suspend timeupdate updateready visibilitychange volumechange waiting",AnimationEvent: "animationend animationiteration animationstart",AudioProcessingEvent: "audioprocess",BeforeUnloadEvent: "beforeunload",TimeEvent: "beginEvent endEvent repeatEvent",OtherEvent: "blocked complete upgradeneeded versionchange",FocusEvent: "blur DOMFocusIn Unimplemented DOMFocusOut Unimplemented focus focusin focusout",MouseEvent: "click contextmenu dblclick mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup show",SensorEvent: "compassneedscalibration Unimplemented userproximity",OfflineAudioCompletionEvent: "complete",CompositionEvent: "compositionend compositionstart compositionupdate",ClipboardEvent: "copy cut paste",DeviceLightEvent: "devicelight",DeviceMotionEvent: "devicemotion",DeviceOrientationEvent: "deviceorientation",DeviceProximityEvent: "deviceproximity",MutationNameEvent: "DOMAttributeNameChanged DOMElementNameChanged",MutationEvent: "DOMAttrModified DOMCharacterDataModified DOMNodeInserted DOMNodeInsertedIntoDocument DOMNodeRemoved DOMNodeRemovedFromDocument DOMSubtreeModified",DragEvent: "drag dragend dragenter dragleave dragover dragstart drop",GamepadEvent: "gamepadconnected gamepaddisconnected",HashChangeEvent: "hashchange",KeyboardEvent: "keydown keypress keyup",MessageEvent: "message message message message",PageTransitionEvent: "pagehide pageshow",PopStateEvent: "popstate",StorageEvent: "storage",SVGEvent: "SVGAbort SVGError SVGLoad SVGResize SVGScroll SVGUnload",SVGZoomEvent: "SVGZoom",TouchEvent: "touchcancel touchend touchenter touchleave touchmove touchstart",TransitionEvent: "transitionend",WheelEvent: "wheel"}var RecentlyLoggedDOMEventTypes = {};for(DOMEvent in DOMEvents){ var DOMEventTypes = DOMEvents[DOMEvent].split(' '); DOMEventTypes.filter(function(DOMEventType){ var DOMEventCategory = DOMEvent + ' '+DOMEventType; document.addEventListener(DOMEventType, function(e){ if(RecentlyLoggedDOMEventTypes[DOMEventCategory]) return; RecentlyLoggedDOMEventTypes[DOMEventCategory] = true; setTimeout(function(){ RecentlyLoggedDOMEventTypes[DOMEventCategory] = false }, 5000); var isActive = e.target==document.activeElement; if(isActive) { console.info(DOMEventCategory, ' target=', e.target, ' active=', document.activeElement, ' isActive=', true ); } else { console.log(DOMEventCategory, ' target=', e.target, ' active=', document.activeElement, ' isActive=', false ); } }, true); });} 这篇关于是否可以以编程方式捕获浏览器中页面上的所有事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 19:04