.aligncenter { clear: both; display: block; margin-left: auto; margin-right: auto }
.crayon-line span::after { content: " " }
p { font-size: 15px; text-indent: 2em }
#colorbox.crayon-colorbox,#cboxOverlay.crayon-colorbox,.crayon-colorbox #cboxWrapper { position: absolute; top: 0; left: 0; z-index: 9999; overflow: hidden }
#cboxOverlay.crayon-colorbox { position: fixed; width: 100%; height: 100% }
.crayon-colorbox #cboxMiddleLeft,.crayon-colorbox #cboxBottomLeft { clear: left }
.crayon-colorbox #cboxContent { position: relative }
.crayon-colorbox #cboxLoadedContent { overflow: auto }
.crayon-colorbox #cboxTitle { display: none !important }
.crayon-colorbox #cboxLoadingOverlay,.crayon-colorbox #cboxLoadingGraphic { position: absolute; top: 0; left: 0; width: 100%; height: 100% }
.crayon-colorbox #cboxPrevious,.crayon-colorbox #cboxNext,.crayon-colorbox #cboxClose,.crayon-colorbox #cboxSlideshow { cursor: pointer }
.crayon-colorbox .cboxPhoto { float: left; margin: auto; border: 0; display: block; max-width: none }
.crayon-colorbox .cboxIframe { width: 100%; height: 100%; display: block; border: 0 }
#colorbox.crayon-colorbox,.crayon-colorbox #cboxContent,.crayon-colorbox #cboxLoadedContent { }
#cboxOverlay.crayon-colorbox { background: #000 }
#colorbox.crayon-colorbox { outline: 0 }
.crayon-colorbox #cboxContent { margin-top: 20px; background: #000 }
.crayon-colorbox .cboxIframe { background: #fff }
.crayon-colorbox #cboxError { padding: 50px; border: 1px solid #ccc }
.crayon-colorbox #cboxLoadedContent { border: 5px solid #000; background: #fff }
.crayon-colorbox #cboxTitle { position: absolute; top: -20px; left: 0; color: #ccc }
.crayon-colorbox #cboxCurrent { position: absolute; top: -20px; right: 0; color: #ccc }
.crayon-colorbox #cboxPrevious,.crayon-colorbox #cboxNext,.crayon-colorbox #cboxSlideshow,.crayon-colorbox #cboxClose { border: 0; padding: 0; margin: 0; overflow: visible; width: auto; background: 0 }
.crayon-colorbox #cboxPrevious:active,.crayon-colorbox #cboxNext:active,.crayon-colorbox #cboxSlideshow:active,.crayon-colorbox #cboxClose:active { outline: 0 }
.crayon-colorbox #cboxSlideshow { position: absolute; top: -20px; right: 90px; color: #fff }
.crayon-colorbox #cboxContent { margin-top: 0 }
.crayon-colorbox #cboxLoadedContent { border: 0 }
#crayon-main-wrap .form-table th { width: 100px }
#crayon-log { display: none; max-height: 200px; border-color: #dfdfdf; background-color: white; border-width: 1px; border-style: solid; margin: 1px; padding: 3px; overflow: auto; white-space: pre; margin-bottom: 5px }
.crayon-span,.crayon-span-5,.crayon-span-10,.crayon-span-50,.crayon-span-100,.crayon-span-110 { line-height: 24px; display: inline-block }
.crayon-span-5 { min-width: 5px }
.crayon-span-10 { min-width: 10px }
.crayon-span-50 { min-width: 50px }
.crayon-span-100 { min-width: 100px }
.crayon-span-110 { min-width: 117px }
.crayon-span-margin { margin-left: 5px }
#height_mode,#width_mode { min-width: 65px }
.crayon-error { color: #F00 }
.crayon-success { color: #00F }
.crayon-warning { color: #ff8000 }
.crayon-help { min-height: 30px; padding: 5px 10px }
.crayon-help .crayon-help-close,.crayon-help .crayon-help-close:active,.crayon-help .crayon-help-close:hover { text-decoration: none; float: right; color: #000 }
.crayon-help span,.crayon-help a { margin: 0; padding: 0; font-size: 12px }
#crayon-log-text { font: 11px/13px Monaco, "MonacoRegular", "Courier New", monospace }
#crayon-log-controls { float: left; margin-right: 5px }
.crayon-table { font-size: 12px; border: 1px solid #999; padding: 0; margin: 0; margin-top: 12px }
.crayon-table td { vertical-align: top; border-bottom: 1px solid #AAA; padding: 0 6px; margin: 0; background: #EEE }
.crayon-table-light td { background: #f8f8f8 }
.crayon-table-header td { font-weight: bold; background: #CCC }
.crayon-table-last td,.crayon-table tr:last-child td { border: 0 }
#lang-info div { padding: 5px 0 }
.crayon-table .not-parsed { color: #F00 }
.crayon-table .parsed-with-errors { color: #f90 }
.crayon-table .successfully-parsed { color: #77a000 }
#crayon-live-preview,#crayon-log-wrapper { padding: 0; width: 100%; float: left; clear: both }
#crayon-live-preview { float: none; padding: 0 }
#crayon-logo { text-align: center }
#crayon-info,#crayon-info td { border: 0; padding: 0 5px; margin: 0 }
.crayon-admin-button { display: inline-block; text-align: center }
#crayon-subsection-langs-info { margin-top: 5px }
#crayon-theme-editor-admin-buttons { display: inline }
#crayon-theme-editor-admin-buttons .crayon-admin-button { margin-left: 5px }
#crayon-theme-info { display: table; padding: 0; margin: 0; margin-top: 5px }
#crayon-theme-info>div { display: table-cell; vertical-align: middle }
#crayon-theme-info .content * { float: left }
#crayon-theme-info .field { font-weight: bold }
#crayon-theme-info .field,#crayon-theme-info .value { margin-left: 5px }
#crayon-theme-info .description.value { font-style: italic; color: #999 }
#crayon-theme-info .type { text-align: center; min-width: 120px; font-weight: bold; border-right: 1px solid #ccc; padding-right: 5px }
#crayon-theme-info .type.stock { color: #666 }
#crayon-theme-info .type.user { color: #5b9a00 }
#crayon-editor-table td { vertical-align: top }
.small-icon { width: 24px; height: 24px; display: inline-block; margin: 5px 5px 0 0 }
#twitter-icon { background: url("../images/twitter.png") }
#gmail-icon { background: url("../images/google.png") }
#docs-icon { background: url("../images/docs.png") }
#git-icon { background: url("../images/github.png") }
#wp-icon { background: url("../images/wordpress-blue.png") }
#donate-icon { background: url("../images/donate.png"); width: 75px }
#crayon-donate,#crayon-donate input { margin: 0; display: inline; padding: 0 }
#crayon-theme-editor-info a { text-decoration: none !important; font-style: italic !important; color: #666 !important }
#crayon-main-wrap .form-table .note { font-style: italic; color: #999 }
#crayon-change-code-text { width: 400px; height: 300px }
.crayon-syntax { overflow: hidden !important; position: relative !important; text-align: left; direction: ltr !important }
.crayon-syntax div { background: 0; border: 0; padding: 0; margin: 0; text-align: left }
.crayon-syntax.crayon-loading { visibility: hidden }
.crayon-syntax,.crayon-syntax .crayon-main,.crayon-syntax .crayon-toolbar,.crayon-syntax .crayon-info,.crayon-syntax .crayon-plain,.crayon-syntax .crayon-code { width: 100% }
.crayon-syntax .crayon-main,.crayon-syntax .crayon-plain { overflow: auto }
.crayon-syntax,.crayon-syntax .crayon-main,.crayon-syntax .crayon-plain,.crayon-syntax .crayon-table { padding: 0; margin: 0 }
.crayon-syntax-inline { margin: 0 2px; padding: 0 2px }
.crayon-syntax .crayon-table { border: none !important; background: none !important; padding: 0 !important; margin-top: 0 !important; margin-right: 0 !important; margin-bottom: 0 !important; width: auto !important; border-spacing: 0 !important; border-collapse: collapse !important; table-layout: auto !important }
.crayon-syntax .crayon-table td,.crayon-syntax .crayon-table tr { padding: 0 !important; border: none !important; background: 0; vertical-align: top !important; margin: 0 !important }
.crayon-syntax .crayon-invisible { display: none !important }
.crayon-plain-tag { margin-bottom: 12px }
.crayon-popup .crayon-plain { display: block !important; width: 100% !important; height: 100% !important; opacity: 100 !important; position: relative !important }
.crayon-popup-window { background: #fff }
.crayon-syntax .crayon-num { text-align: center; padding: 0 5px; margin: 0 }
.crayon-syntax .crayon-toolbar { position: relative; overflow: hidden; z-index: 4 }
.crayon-syntax .crayon-info { position: absolute; overflow: hidden; display: none; z-index: 3; padding: 0; min-height: 18px; line-height: 18px }
.crayon-syntax .crayon-info div { padding: 2px !important; text-align: center }
.crayon-syntax .crayon-toolbar span { padding: 0 4px !important }
.crayon-syntax .crayon-toolbar .crayon-button { display: inline; float: left !important; position: relative; width: 24px; background-repeat: no-repeat; line-height: 15px; border: 0; text-decoration: none }
.crayon-toolbar .crayon-button,.crayon-toolbar .crayon-button:hover,.crayon-toolbar .crayon-button.crayon-pressed:hover { background-position: 0 center }
.crayon-toolbar .crayon-button.crayon-pressed,.crayon-toolbar .crayon-button:active,.crayon-toolbar .crayon-button.crayon-pressed:active { background-position: -24px 0 }
.crayon-toolbar .crayon-button.crayon-popup-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-popup-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-popup-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 0 }
.crayon-toolbar .crayon-button.crayon-copy-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-copy-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-copy-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 -16px }
.crayon-toolbar .crayon-button.crayon-nums-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-nums-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-nums-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 -32px }
.crayon-toolbar .crayon-button.crayon-plain-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-plain-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-plain-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 -48px }
.crayon-toolbar .crayon-button.crayon-mixed-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-mixed-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-mixed-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 -64px }
.crayon-toolbar .crayon-button.crayon-minimize .crayon-button-icon { background-position: 0 -80px; background-color: transparent !important }
.crayon-toolbar .crayon-button.crayon-expand-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-expand-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-expand-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 -96px }
.crayon-toolbar .crayon-button.crayon-wrap-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-wrap-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-wrap-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 -112px }
.crayon-toolbar .crayon-button.crayon-popup-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-popup-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-popup-button.crayon-pressed:active .crayon-button-icon { background-position: -24px 0 }
.crayon-toolbar .crayon-button.crayon-copy-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-copy-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-copy-button.crayon-pressed:active .crayon-button-icon { background-position: -24px -16px }
.crayon-toolbar .crayon-button.crayon-nums-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-nums-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-nums-button.crayon-pressed:active .crayon-button-icon { background-position: -24px -32px }
.crayon-toolbar .crayon-button.crayon-plain-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-plain-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-plain-button.crayon-pressed:active .crayon-button-icon { background-position: -24px -48px }
.crayon-toolbar .crayon-button.crayon-mixed-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-mixed-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-mixed-button.crayon-pressed:active .crayon-button-icon { background-position: -24px -64px }
.crayon-toolbar .crayon-button.crayon-minimize .crayon-button-icon { background-position: -24px -80px; background-color: transparent !important }
.crayon-toolbar .crayon-button.crayon-expand-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-expand-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-expand-button.crayon-pressed:active .crayon-button-icon { background-position: -24px -96px }
.crayon-toolbar .crayon-button.crayon-wrap-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-wrap-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-wrap-button.crayon-pressed:active .crayon-button-icon { background-position: -24px -112px }
.crayon-syntax .crayon-toolbar .crayon-language { padding-right: 8px !important }
.crayon-syntax .crayon-title,.crayon-syntax .crayon-language { float: left }
.crayon-main::-webkit-scrollbar,.crayon-plain::-webkit-scrollbar { height: 6px; overflow: visible; width: 6px; background: #EEE }
.crayon-main::-webkit-scrollbar-thumb,.crayon-plain::-webkit-scrollbar-thumb { background-color: #CCC; border: 1px solid #AAA; min-height: 8px; padding: 0; border-width: 1px }
.crayon-main::-webkit-scrollbar-button,.crayon-plain::-webkit-scrollbar-button { height: 0; width: 0; padding: 0 }
.crayon-main::-webkit-scrollbar-track,.crayon-plain::-webkit-scrollbar-track { border-width: 0 0 0 4px; border: 1px solid #BBB; border-right: 0; border-bottom: 0 }
.crayon-main::-webkit-scrollbar-corner,.crayon-plain::-webkit-scrollbar-corner { background: #EEE }
.crayon-main::-webkit-scrollbar-thumb:hover,.crayon-plain::-webkit-scrollbar-thumb:hover { background: #AAA; border: 1px solid #777 }
.crayon-syntax .crayon-pre,.crayon-syntax pre { color: #000; white-space: pre; margin: 0; padding: 0; overflow: visible; background: none !important; border: none !important }
.crayon-syntax .crayon-line { padding: 0 5px }
.crayon-syntax.crayon-wrapped .crayon-line { white-space: pre-wrap !important; height: auto }
.crayon-syntax-inline .crayon-pre,.crayon-syntax-inline pre { white-space: normal }
.crayon-syntax-inline-nowrap .crayon-pre,.crayon-syntax-inline-nowrap pre { white-space: pre }
.crayon-syntax { font-family: Monaco, "MonacoRegular", "Courier New", monospace; font-weight: 500 }
.crayon-syntax .crayon-toolbar *::selection,.crayon-syntax .crayon-nums *::selection { background: transparent }
.crayon-table .crayon-nums-content { white-space: nowrap }
.crayon-syntax .crayon-num,.crayon-syntax .crayon-pre .crayon-line,.crayon-syntax .crayon-toolbar *,.crayon-syntax .crayon-pre * { font-family: inherit; font-size: inherit !important; line-height: inherit !important; font-weight: inherit !important; height: inherit }
.crayon-syntax .crayon-toolbar .crayon-button .crayon-button-icon { background-image: url("../images/toolbar/buttons.png"); height: 16px !important; width: 100%; position: absolute; left: 0; top: 50%; margin-top: -8px }
.crayon-syntax .crayon-toolbar .crayon-tools { position: absolute; right: 0 }
.crayon-syntax.crayon-expanded { position: absolute !important; margin: 0 !important }
.crayon-syntax.crayon-expanded .crayon-main { overflow: hidden !important }
.crayon-placeholder { width: 100% !important }
.crayon-toolbar-visible .crayon-toolbar { position: relative !important; margin-top: 0 !important; display: block !important }
.crayon-syntax.crayon-expanded .crayon-toolbar .crayon-tools { position: relative; right: auto; float: left !important }
.crayon-syntax .crayon-plain-wrap { height: auto !important; padding: 0 !important; margin: 0 !important }
.crayon-syntax .crayon-plain { width: 100%; height: 100%; position: absolute; opacity: 0; padding: 0 5px; margin: 0; border: 0; white-space: pre; overflow: auto; color: #000; background: #FFF }
.crayon-wrapped .crayon-plain { white-space: pre-wrap }
.bbp-body .crayon-syntax { clear: none !important }
.crayon-minimized .crayon-toolbar { cursor: pointer }
.crayon-minimized .crayon-plain-wrap,.crayon-minimized .crayon-main,.crayon-minimized .crayon-toolbar .crayon-tools * { display: none !important }
.crayon-minimized .crayon-toolbar .crayon-tools .crayon-minimize { display: block !important }
.crayon-minimized .crayon-toolbar { position: relative !important }
.crayon-syntax.crayon-minimized .crayon-toolbar { border-bottom: none !important }
.crayon-te *,#crayon-te-bar-content { font-family: "Lucida Grande", Arial, sans-serif !important; font-size: 12px }
.crayon-te input[type="text"],.crayon-te textarea { background: #f9f9f9; border: 1px solid #CCC; padding: 2px 4px; border-width: 1px; border-style: solid }
.crayon-te #crayon-code { font-family: monospace !important }
#crayon-te-content,#crayon-te-table { width: 100%; height: auto !important }
#crayon-range,#crayon-mark { width: 100px }
#crayon-te-table th,#crayon-te-table td { vertical-align: top; text-align: left }
.rtl #crayon-te-table th,.rtl #crayon-te-table td { text-align: right }
#crayon-te-table .crayon-tr-center td,#crayon-te-table .crayon-tr-center th { vertical-align: middle }
#crayon-te-table .crayon-nowrap { white-space: nowrap }
#crayon-te-bar { position: absolute; top: 0; left: 0; width: 100% }
#crayon-te-bar-content { border: 1px solid #666; border-bottom: 0; height: 26px; line-height: 25px; padding: 0 8px; padding-right: 0; background-color: #222; color: #cfcfcf }
#crayon-te-bar-content a { line-height: 25px; padding: 5px 10px; color: #DDD; font-weight: bold; text-decoration: none !important }
#crayon-te-bar-content a:hover { color: #FFF }
.crayon-te-seperator { color: #666; margin: 0; padding: 0 }
#crayon-te-bar-block { height: 34px; width: 100% }
#crayon-te-title { float: left }
#crayon-te-controls { float: right }
#crayon-url-th { vertical-align: top !important; padding-top: 5px }
.crayon-te-heading { font-size: 14px; font-weight: bold }
#crayon-te-settings-info { text-align: center }
.crayon-te-section { font-weight: bold; padding: 0 10px }
#crayon-te-sub-section { margin-left: 10px }
#crayon-te-sub-section .crayon-te-section { font-weight: normal; padding: 0 }
#crayon-code { height: 200px; white-space: pre }
#crayon-code,#crayon-url { width: 555px !important }
.crayon-disabled { background: #EEE !important }
.qt_crayon_highlight { background-image: linear-gradient(bottom,#daf2ff,white) !important }
.qt_crayon_highlight:hover { background: #ddebf2 !important }
.crayon-tag-editor-button-wrapper { display: inline-block }
.mce_crayon_tinymce { padding: 0 !important; margin: 2px 3px !important }
.mce-i-crayon_tinymce,.mce_crayon_tinymce { background: url("../images/crayon_tinymce.png") 0 0 !important }
a.mce_crayon_tinymce { background-position: 2px 0 !important }
.wp_themeSkin .mceButtonEnabled:hover span.mce_crayon_tinymce,.wp_themeSkin .mceButtonActive span.mce_crayon_tinymce { background-position: -20px 0 }
.wp_themeSkin span.mce_crayon_tinymce { background: none !important }
#crayon-te-table { margin-top: 26px; padding: 10px; border-collapse: separate !important; border-spacing: 2px !important }
#crayon-te-table th { width: 100px }
#crayon-te-clear { color: #666; background-color: #f4f4f4; border: 1px solid #CCC; margin-left: 8px }
#crayon-title { width: 360px }
#TB_window.crayon-te-ajax { overflow: auto !important }
#TB_window.crayon-te-ajax,#TB_window.crayon-te-ajax #TB_ajaxContent,#TB_window.crayon-te-ajax #TB_title { width: 680px !important }
#TB_window.crayon-te-ajax #TB_ajaxContent { padding: 0 !important; margin: 0 !important; width: 100% !important; height: auto !important; margin-top: 28px !important }
#TB_window.crayon-te-ajax #TB_title { position: fixed !important }
#TB_window.crayon-te-ajax #TB_title .crayon-te-submit { margin-top: 3px !important; float: right !important }
#TB_window.crayon-te-ajax a { color: #2587e2; text-decoration: none }
#TB_window.crayon-te-ajax a:hover { color: #499ce9 }
.crayon-te-quote { background: #DDD; padding: 0 2px }
#crayon-te-submit-wrapper { display: none }
#crayon-te-clear { display: none; margin: 0; margin-top: 10px }
.crayon-syntax-pre { background: red; white-space: pre; overflow: auto; display: block }
.crayon-question { padding: 1px 4px !important; text-decoration: none !important; color: #83b3cb !important; height: 15px !important; width: 15px !important }
.crayon-question:hover { background: #83b3cb !important; color: white !important; height: 15px !important; width: 15px !important }
.crayon-setting-changed,.crayon-setting-selected { background: #fffaad !important }
.crayon-question:hover { color: white; background: #a6d6ef }
#crayon-te-warning { display: none }
.crayon-te-info { padding: 5px !important; margin: 2px 0 !important }
#crayon-te-submit { margin-bottom: 5px }
.crayon-theme-github { margin-bottom: 25px !important; border: 1px solid #dedede !important; background-color: #f8f8ff !important; font-size: 100% !important; line-height: 130% !important }
.crayon-theme-github .crayon-toolbar { border-bottom: 1px solid #dedede !important; background-color: #eee !important }
.crayon-theme-github .crayon-toolbar .crayon-language,.crayon-theme-github .crayon-toolbar .crayon-title { font-size: 80% !important; color: #666 !important }
.crayon-theme-github .crayon-table .crayon-nums { background-color: #eee !important }
.crayon-theme-github .crayon-table .crayon-nums-content { padding-top: 5px !important; padding-bottom: 3px !important }
.crayon-theme-github .crayon-table .crayon-num { min-width: 1.2em !important; border-right: 1px solid #dedede !important; text-align: right !important; color: #aaa !important }
.crayon-theme-github .crayon-pre { padding-top: 5px !important; padding-bottom: 3px !important }
.crayon-theme-github .crayon-marked-line { background: #fffee2 !important }
.crayon-theme-github .crayon-marked-num { color: #1561ac !important; background: #b3d3f4 !important; border-width: 1px !important; border-color: #5999d9 !important }
.crayon-theme-github .crayon-pre .crayon-c { color: #999 !important; font-style: italic !important }
.crayon-theme-github .crayon-pre .crayon-s { color: #d14 !important }
.crayon-theme-github .crayon-pre .crayon-p { color: #b85c00 !important }
.crayon-theme-github .crayon-pre .crayon-ta { color: #FF0000 !important }
.crayon-theme-github .crayon-pre .crayon-k { color: teal !important }
.crayon-theme-github .crayon-pre .crayon-st { color: #000 !important; font-weight: bold !important }
.crayon-theme-github .crayon-pre .crayon-r { color: #000 !important; font-weight: bold !important }
.crayon-theme-github .crayon-pre .crayon-t { color: #800080 !important; font-weight: bold !important }
.crayon-theme-github .crayon-pre .crayon-m { color: #800080 !important }
.crayon-theme-github .crayon-pre .crayon-i { color: #000 !important }
.crayon-theme-github .crayon-pre .crayon-e { color: teal !important }
.crayon-theme-github .crayon-pre .crayon-v { color: #002D7A !important }
.crayon-theme-github .crayon-pre .crayon-cn { color: #099 !important }
.crayon-theme-github .crayon-pre .crayon-o { color: #006fe0 !important }
.crayon-theme-github .crayon-pre .crayon-sy { color: #333 !important }
.crayon-theme-github .crayon-pre .crayon-n { color: #666 !important; font-style: italic }
.crayon-theme-github .crayon-pre .crayon-f { color: #999 !important }
.crayon-theme-github .crayon-pre .crayon-h { color: #006fe0 !important }
.crayon-syntax .crayon-pre,.crayon-syntax pre { white-space: initial }
img { margin-top: 10px; margin-bottom: 10px }
img { margin-top: 10px; margin-bottom: 10px }

在上一篇《从Chrome源码看浏览器如何构建DOM树》介绍了blink如何创建一棵DOM树,在这一篇将介绍事件机制。

上一篇还有一个地方未提及,那就是在构建完DOM之后,浏览器将会触发DOMContentLoaded事件,这个事件是在处理tokens的时候遇到EndOfFile标志符时触发的:

 
 
 
 
 
 

C++

 
if (it->type() == HTMLToken::EndOfFile) {
// The EOF is assumed to be the last token of this bunch.
ASSERT(it + 1 == tokens->end());
// There should never be any chunks after the EOF.
ASSERT(m_speculations.isEmpty());
prepareToStopParsing();
break;
}
1
2
3
4
5
6
7
8
if(it->type()==HTMLToken::EndOfFile){
  // The EOF is assumed to be the last token of this bunch.
  ASSERT(it+1==tokens->end());
  // There should never be any chunks after the EOF.
  ASSERT(m_speculations.isEmpty());
  prepareToStopParsing();
  break;
}

上面代码第1行,遇到结尾的token时,将会在第6行停止解析。这是最后一个待处理的token,一般是跟在</html>后面的一个\EOF标志符来的。

第6行的prepareToStopParsing,会在Document的finishedParseing里面生成一个事件,再调用dispatchEvent,进一步调用监听函数:

 
 
 
 
 
 

C++

 
void Document::finishedParsing() {
  dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
}
1
2
3
voidDocument::finishedParsing(){
 dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
}

这个dispatchEvent是EventTarget这个类的成员函数。在上一篇描述DOM的结点数据结构时将Node作为根结点,其实Node上面还有一个类,就是EventTarget。我们先来看一下事件的数据结构是怎么样的:

1. 事件的数据结构

画出事件相关的类图:

在最顶层的EventTarget提供了三个函数,分别是添加监听add、删除监听remove、触发监听fire。一个典型的访问者模式我在《Effective前端5:减少前端代码耦合》提到了,这里重点看一下blink实际上是怎么实现的。

在Node类组合了一个EventTargetDataMap,这是一个哈希map,并且它是静态成员变量。它的key值是当前结点Node实例的指针,value值是事件名称和对应的listeners。如果画一个示例图,它的存储是这样的:

如上,按照正常的思维,存放事件名称和对应的访问者应该是用一个哈希map,但是blink却是用的向量vector + pair,这就导致在查找某个事件的访问者的时候,需要循环所有已添加的事件名称依次比较字符串值是否相等。为什么要用循环来做而不是map,这在它的源码注释做了说明:

 
 
 
 
 
 

C++

 
// We use HeapVector instead of HeapHashMap because
// - HeapVector is much more space efficient than HeapHashMap.
// - An EventTarget rarely has event listeners for many event types, and
// HeapVector is faster in such cases.
HeapVector<std::pair<AtomicString, Member<EventListenerVector>>, 2> m_entries;
1
2
3
4
5
// We use HeapVector instead of HeapHashMap because
//  - HeapVector is much more space efficient than HeapHashMap.
//  - An EventTarget rarely has event listeners for many event types, and
//    HeapVector is faster in such cases.
HeapVector<std::pair<AtomicString,Member<EventListenerVector>>,2>m_entries;

意思是说使用vector比使用map更加节省空间,并且一个dom节点往往不太可能绑了太多的事件类型。这就启示我们写代码要根据实际情况灵活处理。

同时还有一个比较有趣的事情,就是webkit用了一个EventTargetDataMap存放所有节点绑定的事件,它是一个static静态成员变量,被所有Node的实例所共享,由于不同的实例的内存地址不一样,所以它的key不一样,就可以通过内存地址找到它绑的所有事件,即上面说的vector结构。为什么它要用一个类似于全局的变量?按照正常思维,每个Node结点绑的事件是独立的,那应该把绑的事件作为每个Node实例独立的数据,搞一个全局的还得用一个map作一个哈希映射。

一个可能的原因是EventTarget是作为所有DOM结点的事件目标的类,除了Node之外,还有FileReader、AudioNode等也会继承于EventTarget,它们有另外一个EventTargetData。把所有的事件都放一起了,应该会方便统一处理。

这个时候你可能会冒出另外一个问题,这个EventTargetDataMap是什么释放绑定的事件的,我把一个DOM结点删了,它会自动去释放绑定的的事件吗?换句话说,删除掉一个结点前需不需要先off掉它的事件?

2. DOM结点删除与事件解绑

从源码可以看到,Node的析构函数并没有去释放当前Node绑定的事件,所以它是不是不会自动释放事件?为验证,我们在添加绑定一个事件后、删掉结点后分别打印这个map里面的数据,为此给Node添加一个打印的函数:

 
 
 
 
 
 

C++

 
void Node::printEventMap(){
EventTargetDataMap::iterator it = eventTargetDataMap().begin();
LOG (INFO) << "print event map: ";
while(it != eventTargetDataMap().end()){
LOG(INFO) << ((Element*)it->key.get())->tagName();
++it;
}
}
1
2
3
4
5
6
7
8
voidNode::printEventMap(){
    EventTargetDataMap::iterator it=eventTargetDataMap().begin();
    LOG(INFO)<<"print event map: ";
    while(it!=eventTargetDataMap().end()){
        LOG(INFO)<<((Element*)it->key.get())->tagName();
        ++it;
    }  
}

在上面的第5行,循环打印出所有Node结点的标签名。

同时试验的html如下:

 
 
 
 
 
 

XHTML

 
<p id="text">hello, world</p>
<script>
function clickHandle(){
console.log("click");
}
document.getElementById("text").addEventListener("click", clickHandle);
document.getElementById("text").remove();
document.addEventListener("DOMContentLoaded", function(){
console.log("loaded");
});
</script>
1
2
3
4
5
6
7
8
9
10
11
<p id="text">hello, world</p>
<script>
    functionclickHandle(){
        console.log("click");
    }
    document.getElementById("text").addEventListener("click",clickHandle);
    document.getElementById("text").remove();
    document.addEventListener("DOMContentLoaded",function(){
        console.log("loaded");
    });
</script>

打印的结果如下:

[21755:775:0204/181452.402843:INFO:Node.cpp(1910)] print event map:

[21755:775:0204/181452.403048:INFO:Node.cpp(1912)] “P”

[21755:775:0204/181452.404114:INFO:Node.cpp(1910)] print event map:

[21755:775:0204/181452.404287:INFO:Node.cpp(1912)] “P”

[21755:775:0204/181452.404466:INFO:Node.cpp(1912)] “#document”

可以看到remove了p结点之后,它的事件依然存在。

我们看一下blink在remove里面做了什么:

 
 
 
 
 
 

C++

 
void Node::remove(ExceptionState& exceptionState) {
if (ContainerNode* parent = parentNode())
parent->removeChild(this, exceptionState);
}
1
2
3
4
voidNode::remove(ExceptionState&exceptionState){
  if(ContainerNode*parent=parentNode())
    parent->removeChild(this,exceptionState);
}

remove是后来W3C新加的api,所以在remove里面调的是老的removeChild,removeChild的关键代码如下:

 
 
 
 
 
 

C++

 
Node* previousChild = child->previousSibling();
Node* nextChild = child->nextSibling();
if (nextChild)
nextChild->setPreviousSibling(previousChild);
if (previousChild)
previousChild->setNextSibling(nextChild);
if (m_firstChild == &oldChild)
setFirstChild(nextChild);
if (m_lastChild == &oldChild)
setLastChild(previousChild);

oldChild.setPreviousSibling(nullptr);
oldChild.setNextSibling(nullptr);
oldChild.setParentOrShadowHostNode(nullptr);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Node*previousChild=child->previousSibling();
Node*nextChild=child->nextSibling();
if(nextChild)
  nextChild->setPreviousSibling(previousChild);
if(previousChild)
  previousChild->setNextSibling(nextChild);
if(m_firstChild==&oldChild)
  setFirstChild(nextChild);
if(m_lastChild==&oldChild)
  setLastChild(previousChild);
 
oldChild.setPreviousSibling(nullptr);
oldChild.setNextSibling(nullptr);
oldChild.setParentOrShadowHostNode(nullptr);

前面几行是重新设置DOM树的结点关系,比较好理解。最后面三行,把删除掉的结点的兄弟指针和父指针置为null,注意这里并没有把它delete掉,只是把它隔离开来。所以把它remove掉之后, 这个结点在内存里面依旧存在,你依然可以获取它的innerText,把它重新append到body里面(但是不推荐这么做)。同时事件依然存在那个map里面。

什么时候这个节点会被真正的析构呢?发生在GC回收的时候,GC回收的时候会把DOM结点的内存释放,并且会删掉map里面的数据。为验证,在启动Chrome的时候加上参数:

 
 
 
 
 
 

Shell

 
chromium test.html --js-flags='--expose_gc'
1
chromium test.html  --js-flags='--expose_gc'

这样可以调用window.gc触发gc回收,然后在上面的js demo代码后面加上:

 
 
 
 
 
 

JavaScript

 
setTimeout(function(){
//添加这个事件是为了触发Chrome源码里面添加的打印log
document.addEventListener("DOMContentLoaded", function(){});
setTimeout(function(){
window.gc();
document.addEventListener("DOMContentLoaded", function(){});
}, 3000);
}, 3000);
1
2
3
4
5
6
7
8
setTimeout(function(){
    //添加这个事件是为了触发Chrome源码里面添加的打印log
    document.addEventListener("DOMContentLoaded",function(){});
    setTimeout(function(){
        window.gc();
        document.addEventListener("DOMContentLoaded",function(){});
    },3000);
},3000);

打印的结果:

[Node.cpp(1912)] print event map:

[Node.cpp(1914)] “P”

[Node.cpp(1914)] “#document”

[Element.cpp(186)] destroy element “p”

[Node.cpp(1912)] print event map:

[Node.cpp(1914)] “#document”

后面三行是执行了GC回收后的结果——析构p标签并更新存放事件的数据结构。

所以说删掉一个DOM结点,并不需要手动去释放它的事件。

需要注意的是DOM结点一旦存在一个引用,即使你把它remove掉了,GC也不会去回收,如下:

 
 
 
 
 
 

XHTML

 
<script>
var p = document.getElementById("text");
p.remove();
window.gc();
</script>
1
2
3
4
5
<script>
    varp=document.getElementById("text");
    p.remove();
    window.gc();
</script>

执行了window.gc之后并不会去回收p的内存空间以及它的事件。因为还存在一个p的变量指向它,而如果将p置为null,如下:

 
 
 
 
 
 

XHTML

 
<script>
var p = document.getElementById("text");
p.remove();
p = null;
window.gc();
</script>
1
2
3
4
5
6
<script>
    varp=document.getElementById("text");
    p.remove();
    p=null;
    window.gc();
</script>

最后的GC就管用了,或者p离开了作用域:

 
 
 
 
 
 

C++

 
<script>
!function(){
var p = document.getElementById("text");
p.remove();
}()
window.gc();
</script>
1
2
3
4
5
6
7
<script>
!function(){
    varp=document.getElementById("text");
    p.remove();
}()
window.gc();
</script>

自动销毁,p结点没有人引用了,能够自动GC回收。

还有一个问题一直困扰着我,那就是监听X按钮的click,然后把它的父容器如弹框给删了,这样它自已本身也删了,但是监听函数还可以继续执行,实体都没有了,为什么绑在它身上的函数还可以继续执行呢?通过上面的分析,应该可以找到答案:删掉之后GC并不会立刻回收和释放事件,因为在执行监听函数的时候,里面有个this指针指向了该节点,并且this是只读的,你不能把它置成null。所以只有执行完了回调函数,离开了作用域,this才会销毁,才有可能被GC回收。

还有一种绑事件的方式,没有讨论:

3. DOM Level 0事件

就是使用dom结点的onclick、onfocus等属性,添加事件,由于这个提得比较早,所以它的兼容性最好。如下:

 
 
 
 
 
 

JavaScript

 
function clickHandle(){
console.log("addEventListener click");
}
var p = document.getElementById("text");
p.addEventListener("click", clickHandle);
p.onclick = function(){
console.log("onclick trigger");
};
1
2
3
4
5
6
7
8
functionclickHandle(){
    console.log("addEventListener click");
}
varp=document.getElementById("text");
p.addEventListener("click",clickHandle);
p.onclick=function(){
    console.log("onclick trigger");  
};

如果点击p标签,将会触发两次,一次是addEventListener绑定的,另一次是onclick绑定的。onclick是如何绑定的呢:

 
 
 
 
 
 

C++

 
bool EventTarget::setAttributeEventListener(const AtomicString& eventType,
EventListener* listener) {
clearAttributeEventListener(eventType);
if (!listener)
return false;
return addEventListener(eventType, listener, false);
}
1
2
3
4
5
6
7
boolEventTarget::setAttributeEventListener(constAtomicString&eventType,
                                            EventListener*listener){
  clearAttributeEventListener(eventType);
  if(!listener)
    returnfalse;
  returnaddEventListener(eventType,listener,false);
}

可以看到,最后还是调的上面的addEventListener,只是在此之前要先clear掉上一次绑的属性事件:

 
 
 
 
 
 

C++

 
bool EventTarget::clearAttributeEventListener(const AtomicString& eventType) {
EventListener* listener = getAttributeEventListener(eventType);
if (!listener)
return false;
return removeEventListener(eventType, listener, false);
}
1
2
3
4
5
6
boolEventTarget::clearAttributeEventListener(constAtomicString&eventType){
  EventListener*listener=getAttributeEventListener(eventType);
  if(!listener)
    returnfalse;
  returnremoveEventListener(eventType,listener,false);
}

在clear函数里面会去获取上一次的listener,然后调removeEventListener,关键在于它怎么根据事件名称eventType获取上次listener呢:

 
 
 
 
 
 

C++

 
EventListener* EventTarget::getAttributeEventListener(
const AtomicString& eventType) {
EventListenerVector* listenerVector = getEventListeners(eventType);
if (!listenerVector)
return nullptr;

for (auto& eventListener : *listenerVector) {
EventListener* listener = eventListener.listener();
if (listener->isAttribute() /* && ... */)
return listener;
}
return nullptr;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
EventListener*EventTarget::getAttributeEventListener(
    constAtomicString&eventType){
  EventListenerVector*listenerVector=getEventListeners(eventType);
  if(!listenerVector)
    returnnullptr;
 
  for(auto&eventListener:*listenerVector){
    EventListener*listener=eventListener.listener();
    if(listener->isAttribute()/* && ... */)
      returnlistener;
  }
  returnnullptr;
}

在代码上看很容易理解,首先获取该DOM结点该事件名称的所有listener做个循环,然后判断这个listener是否为属性事件。判断成立,则返回。怎么判断是否为属性事件?那个是实例化事件的时候封装好的了。

从上面的源代码可以很清楚地看到onclick等属性事件只能绑一次,并且和addEventListener的事件不冲突。

关于事件,还有一个很重要的概念,那就是事件的捕获和冒泡。

4. 事件的捕获和冒泡

用以下html做试验:

 
 
 
 
 
 

XHTML

 
<div id="div-1">
<div id="div-2">
<div id="div-3">hello, world</div>
</div>
</div>
1
2
3
4
5
<div id="div-1">
    <div id="div-2">
        <div id="div-3">hello, world</div>
    </div>
</div>

js绑事件如下:

 
 
 
 
 
 

JavaScript

 
var div1 = document.getElementById("div-1"),
div2 = document.getElementById("div-2"),
div3 = document.getElementById("div-3");
function printInfo(event){
console.log(“eventPhase=“ + ””event.eventPhase + " " + this.id);
}
div1.addEventListener("click", printInfo, true);
div2.addEventListener("click", printInfo, true);
div3.addEventListener("click", printInfo, true);

div1.addEventListener("click", printInfo);
div2.addEventListener("click", printInfo);
div3.addEventListener("click", printInfo);

1
2
3
4
5
6
7
8
9
10
11
12
13
vardiv1=document.getElementById("div-1"),
    div2=document.getElementById("div-2"),
    div3=document.getElementById("div-3");
functionprintInfo(event){
    console.log(“eventPhase=“+””event.eventPhase+" "+this.id);
}
div1.addEventListener("click",printInfo,true);
div2.addEventListener("click",printInfo,true);
div3.addEventListener("click",printInfo,true);
 
div1.addEventListener("click",printInfo);
div2.addEventListener("click",printInfo);
div3.addEventListener("click",printInfo);

第三个参数为true,表示监听在捕获阶段,点击p标签之后控制台打印出:

[CONSOLE] “eventPhase=1 div-1”

[CONSOLE] “eventPhase=1 div-2”

[CONSOLE] “eventPhase=2 div-3”

[CONSOLE] “eventPhase=2 div-3”

[CONSOLE] “eventPhase=3 div-2”

[CONSOLE] “eventPhase=3 div-1”

在Event类定义里面可以找到关到eventPhase的定义:

 
 
 
 
 
 

C++

 
enum PhaseType {
kNone = 0,
kCapturingPhase = 1,
kAtTarget = 2,
kBubblingPhase = 3
};
1
2
3
4
5
6
  enumPhaseType{
    kNone=0,
    kCapturingPhase=1,
    kAtTarget=2,
    kBubblingPhase=3
  };

1表示捕获取阶段,2表示在当前目标,3表示冒泡阶段。把上面的phase转化成文字,并把html/body/document也绑上事件,同时at-target只绑一次,那么整一个过程将是这样的:

“capture     document”

“capture     HTML”

“capture     BODY”

“capture     DIV#div-1”,

“capture     DIV#div-2”,

“at-target   DIV#div-3”,

“bubbling   DIV#div-2”,

“bubbling   DIV#div-1”,

“bubbling   BODY”

“bubbling   HTML”

“bubbling   document”

从document一直捕获到目标div3,然后再一直冒泡到document,如果在某个阶段执行了:

 
 
 
 
 
 

JavaScript

 
event.stopPropagation()
1
event.stopPropagation()

那么后续的过程将不会继续,例如在document的capture阶段的click事件里面执行了上面的阻止传播函数,那么控制台只会打印出上面输出的第一行。

在研究blink是如何实现之前,我们先来看一下事件是怎么触发和封装的

5. 事件的触发和封装

以click事件为例,Blink在RenderViewImpl里面收到了外面的进程的消息:

 
 
 
 
 
 

C++

 
// IPC::Listener implementation ----------------------------------------------
bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
// Have the super handle all other messages.
IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
}
1
2
3
4
5
// IPC::Listener implementation ----------------------------------------------
boolRenderViewImpl::OnMessageReceived(constIPC::Message&message){
    // Have the super handle all other messages.
    IPC_MESSAGE_UNHANDLED(handled=RenderWidget::OnMessageReceived(message))
}

上文已提到,RenderViewImpl是页面最基础的一个类,当它收到IPC发来的消息时,根据消息的类型,调用相应的处理函数,由于这是一个input消息,所以它会调:

 
 
 
 
 
 

C++

 
IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent)
1
IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent,OnHandleInputEvent)

上面的IPC_MESSAGE_HANDLER其实是Blink定义的一个宏,这个宏其实就是一个switch-case里面的case。

这个处理函数又会调:

 
 
 
 
 
 

C++

 
WebInputEventResult WebViewImpl::handleInputEvent(
    const WebInputEvent& inputEvent) {
switch (inputEvent.type) {
case WebInputEvent::MouseUp:
eventType = EventTypeNames::mouseup;
gestureIndicator = WTF::wrapUnique(
new UserGestureIndicator(m_mouseCaptureGestureToken.release()));
break;
}
}
1
2
3
4
5
6
7
8
9
10
WebInputEventResult WebViewImpl::handleInputEvent(
   constWebInputEvent&inputEvent){
    switch(inputEvent.type){
      caseWebInputEvent::MouseUp:
        eventType=EventTypeNames::mouseup;
        gestureIndicator=WTF::wrapUnique(
            newUserGestureIndicator(m_mouseCaptureGestureToken.release()));
        break;
    }
}

它里面会根据输入事件的类型如mouseup、touchstart、keybord事件等类型去调不同的函数。click是在mouseup里面处理的,接着在MouseEventManager里面创建一个MouseEvent,并调度事件,即捕获和冒泡:

 
 
 
 
 
 

C++

 
WebInputEventResult MouseEventManager::dispatchMouseEvent(EventTarget* target, const AtomicString& mouseEventType, const PlatformMouseEvent& mouseEvent, EventTarget* relatedTarget, bool checkForListener) {
MouseEvent* event = MouseEvent::create( mouseEventType, targetNode->document().domWindow(), mouseEvent/*...*/);
DispatchEventResult dispatchResult = target->dispatchEvent(event);
return EventHandlingUtil::toWebInputEventResult(dispatchResult);
}
1
2
3
4
5
WebInputEventResult MouseEventManager::dispatchMouseEvent(EventTarget*target,constAtomicString&mouseEventType,constPlatformMouseEvent&mouseEvent,EventTarget*relatedTarget,boolcheckForListener){
    MouseEvent*event=MouseEvent::create(mouseEventType,targetNode->document().domWindow(),mouseEvent/*...*/);
    DispatchEventResult dispatchResult=target->dispatchEvent(event);
    returnEventHandlingUtil::toWebInputEventResult(dispatchResult);
}

上面代码第2行创建MouseEvent,第3行dispatch。我们来看一下这个事件是如何层层封装成一个MouseEvent的:

上图展示了从原始的msg转化成了W3C标准的MouseEvent的过程。Blink的消息处理引擎把msg转化成了WebInputEvent,这个event能够直接静态转化成可读的WebMouseEvent,也就是事件在底层的时候已经被封装成带有相关数据且可读的事件了,上层再把它这些数据转化成W3C规定格式的MouseEvent。

我们重点看下MouseEvent的create函数:

 
 
 
 
 
 

C++

 
MouseEvent* MouseEvent::create(const AtomicString& eventType, AbstractView* view, const PlatformMouseEvent& event, Node* relatedTarget) {
bool isMouseEnterOrLeave = eventType == EventTypeNames::mouseenter ||
eventType == EventTypeNames::mouseleave;
bool isCancelable = !isMouseEnterOrLeave;
bool isBubbling = !isMouseEnterOrLeave;

return MouseEvent::create(
eventType, isBubbling, isCancelable, view, event.position().x()
/*.../*, &event);
}

1
2
3
4
5
6
7
8
9
10
MouseEvent*MouseEvent::create(constAtomicString&eventType,AbstractView*view,constPlatformMouseEvent&event,Node*relatedTarget){
  boolisMouseEnterOrLeave=eventType==EventTypeNames::mouseenter||
                             eventType==EventTypeNames::mouseleave;
  boolisCancelable=!isMouseEnterOrLeave;
  boolisBubbling=!isMouseEnterOrLeave;
 
  returnMouseEvent::create(
      eventType,isBubbling,isCancelable,view,event.position().x()
      /*.../*,&event);
}

从代码第五行可以看到鼠标事件的mouseenter和mouseleave是不会冒泡的。

另外,每个Event都有一个EventPath,记录它冒泡的路径:

在dispatchEvent的时候,会初始化EventPath:

 
 
 
 
 
 

C++

 
void EventPath::initialize() {
if (eventPathShouldBeEmptyFor(*m_node, m_event))
return;

calculatePath();
calculateAdjustedTargets();
calculateTreeOrderAndSetNearestAncestorClosedTree();
}

1
2
3
4
5
6
7
8
voidEventPath::initialize(){
  if(eventPathShouldBeEmptyFor(*m_node,m_event))
    return;
 
  calculatePath();
  calculateAdjustedTargets();
  calculateTreeOrderAndSetNearestAncestorClosedTree();
}

第五行会去计算Path,而这个计算Path的核心逻辑非常简单:

 
 
 
 
 
 

C++

 
void EventPath::calculatePath() {
// For performance and memory usage reasons we want to store the
// path using as few bytes as possible and with as few allocations
// as possible which is why we gather the data on the stack before
// storing it in a perfectly sized m_nodeEventContexts Vector.
HeapVector<Member<Node>, 64> nodesInPath;
Node* current = m_node;
nodesInPath.push_back(current);
while (current) {
current = current->parentNode();
if (current)
nodesInPath.push_back(current);
}
m_nodeEventContexts.reserveCapacity(nodesInPath.size());
for (Node* nodeInPath : nodesInPath) {
m_nodeEventContexts.push_back(NodeEventContext(
nodeInPath, eventTargetRespectingTargetRules(*nodeInPath)));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
voidEventPath::calculatePath(){
  // For performance and memory usage reasons we want to store the
  // path using as few bytes as possible and with as few allocations
  // as possible which is why we gather the data on the stack before
  // storing it in a perfectly sized m_nodeEventContexts Vector.
  HeapVector<Member<Node>,64>nodesInPath;
  Node*current=m_node;
  nodesInPath.push_back(current);
  while(current){
      current=current->parentNode();
      if(current)
        nodesInPath.push_back(current);
  }
  m_nodeEventContexts.reserveCapacity(nodesInPath.size());
  for(Node*nodeInPath:nodesInPath){
    m_nodeEventContexts.push_back(NodeEventContext(
        nodeInPath,eventTargetRespectingTargetRules(*nodeInPath)));
  }
}

第9行的while循环不断地获取当前node的父节点并把它push到一个vector里面,直到null即没有父节点为止。最后再把这个vector push到真正用来存储成员变量。这段代码我们又发现一个有趣的注释,它说明了为什么不直接push到成员变量里面——因为vector变量会自动扩展本身大小,当push的时候容量不足时,会不断地开辟内存,blink的实现是开辟一个单位元素的空间,刚好存放一个元素:

 
 
 
 
 
 

C++

 
ptr = expandCapacity(size() + 1, ptr);
1
ptr=expandCapacity(size()+1,ptr);

所以如果直接push_back到成员变量,会不断地开辟新内存。于是它一开始就初始化了一个size为64的栈变量来存放,减少开辟内存的操作。另外有些vector自动扩充容量的实现,可能是size * 1.5或者size + 10,而不是size + 1,这种情况就会导致有多余的空间没用到。

通过这样的手段,就有了记录事件冒泡路径的EventPath。

6. 事件捕获和冒泡的实现

上面第5点提到的MouseEventManager会调dispatchEvent,这个函数会先创建一个dispatcher,这个dispatcher实例化的时候就会去初始化上面的EventPath,然后再进行dispatch/事件调度:

 
 
 
 
 
 

C++

 
EventDispatcher dispatcher(node, &mediator->event());
DispatchEventResult dispatchResult = dispatcher.dispatch();
1
2
EventDispatcher dispatcher(node,&mediator->event());
DispatchEventResult dispatchResult=dispatcher.dispatch();

所以核心函数就是第2行调的dispatch,而这个函数最核心的3行代码为:

 
 
 
 
 
 

C++

 
if (dispatchEventAtCapturing() == ContinueDispatching) {
if (dispatchEventAtTarget() == ContinueDispatching)
dispatchEventAtBubbling();
}
1
2
3
4
if(dispatchEventAtCapturing()==ContinueDispatching){
  if(dispatchEventAtTarget()==ContinueDispatching)
     dispatchEventAtBubbling();
}

(1)先执行Capturing,然后再执行AtTarget,最后再Bubbling,我们来看一下Capturing函数:

事件捕获

 
 
 
 
 
 

C++

 
inline EventDispatchContinuation EventDispatcher::dispatchEventAtCapturing() {
// Trigger capturing event handlers, starting at the top and working our way
// down.
//改变event的阶段为冒泡
m_event->setEventPhase(Event::kCapturingPhase);
//先处理绑在window上的事件,并且如果event的m_propagationStopped被设置为true
//则返回done状态,不再继续传播
if (m_event->eventPath().windowEventContext().handleLocalEvents(*m_event) &&
m_event->propagationStopped())
return DoneDispatching;
1
2
3
4
5
6
7
8
9
10
inlineEventDispatchContinuation EventDispatcher::dispatchEventAtCapturing(){
  // Trigger capturing event handlers, starting at the top and working our way
  // down.
  //改变event的阶段为冒泡
  m_event->setEventPhase(Event::kCapturingPhase);
  //先处理绑在window上的事件,并且如果event的m_propagationStopped被设置为true
  //则返回done状态,不再继续传播
  if(m_event->eventPath().windowEventContext().handleLocalEvents(*m_event)&&
      m_event->propagationStopped())
    returnDoneDispatching;

上面做了一些初始化的工作后,循环EventPath依次触发响应函数:

 
 
 
 
 
 

C++

 
//从EventPath最后一个元素,即最顶层的父结点开始下滤
for (size_t i = m_event->eventPath().size() - 1; i > 0; --i) {
const NodeEventContext& eventContext = m_event->eventPath()[i];

//触发事件响应函数
eventContext.handleLocalEvents(*m_event);
//如果响应函数设置了stopPropagation,则返回done
if (m_event->propagationStopped())
return DoneDispatching;
}

return ContinueDispatching;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
  //从EventPath最后一个元素,即最顶层的父结点开始下滤
  for(size_ti=m_event->eventPath().size()-1;i>0;--i){
    constNodeEventContext&eventContext=m_event->eventPath()[i];
 
    //触发事件响应函数
    eventContext.handleLocalEvents(*m_event);
    //如果响应函数设置了stopPropagation,则返回done
    if(m_event->propagationStopped())
      returnDoneDispatching;
  }
 
  returnContinueDispatching;
}

注意上面的for循环终止条件的i是大于0,i为0则为currentTarget。而总的size为6,与我们上面demo控制台打印一致。

(2)at-target的处理就很简单了,取i为0的那个Node并触发它的listeners:

 
 
 
 
 
 

C++

 
inline EventDispatchContinuation EventDispatcher::dispatchEventAtTarget() {
m_event->setEventPhase(Event::kAtTarget);
m_event->eventPath()[0].handleLocalEvents(*m_event);
return m_event->propagationStopped() ? DoneDispatching : ContinueDispatching;
}
1
2
3
4
5
inlineEventDispatchContinuation EventDispatcher::dispatchEventAtTarget(){
  m_event->setEventPhase(Event::kAtTarget);
  m_event->eventPath()[0].handleLocalEvents(*m_event);
  returnm_event->propagationStopped()?DoneDispatching:ContinueDispatching;
}

(3)bubbling的处理稍复杂,因为它还要处理cancleBubble的情况,不过总体的逻辑是类似的,核心代码如下:

 
 
 
 
 
 

C++

 
inline void EventDispatcher::dispatchEventAtBubbling() {
// Trigger bubbling event handlers, starting at the bottom and working our way
// up.
size_t size = m_event->eventPath().size();
for (size_t i = 1; i < size; ++i) {
const NodeEventContext& eventContext = m_event->eventPath()[i];
if (m_event->bubbles() && !m_event->cancelBubble()) {
m_event->setEventPhase(Event::kBubblingPhase);
}
eventContext.handleLocalEvents(*m_event);
if (m_event->propagationStopped())
return;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
inlinevoidEventDispatcher::dispatchEventAtBubbling(){
  // Trigger bubbling event handlers, starting at the bottom and working our way
  // up.
  size_t size=m_event->eventPath().size();
  for(size_ti=1;i<size;++i){
    constNodeEventContext&eventContext=m_event->eventPath()[i];
    if(m_event->bubbles()&&!m_event->cancelBubble()){
      m_event->setEventPhase(Event::kBubblingPhase);
    }
    eventContext.handleLocalEvents(*m_event);
    if(m_event->propagationStopped())
      return;
  }
}

可以看到bubbling的for循环是从i = 1开始,和capturing相反。因为bubble是三个阶段最后处理的,所以它不用再返回一个标志了。

上面介绍完了事件的捕获和冒泡,我们注意到一个细节,所有的事件都会先在capture阶段在windows上触发。

综合以上,本文从源码角度介绍了事件的数据结构,从一个侧面解绑事件介绍事件和DOM节点的联系,然后重点分析了事件的捕获及冒泡过程。相信看完本文,对事件的本质会有一个更透彻的理解。

从Chrome源码看浏览器的事件机制的更多相关文章

  1. 从Chrome源码看浏览器如何构建DOM树

    .aligncenter { clear: both; display: block; margin-left: auto; margin-right: auto } p { font-size: 1 ...

  2. 从Chrome源码看JS Array的实现

    .aligncenter { clear: both; display: block; margin-left: auto; margin-right: auto } .crayon-line spa ...

  3. 从Chrome源码看audio/video流媒体实现二(转)

    第一篇主要介绍了Chrome加载音视频的缓冲控制机制和编解码基础,本篇将比较深入地介绍解码播放的过程.以Chromium 69版本做研究. 由于Chromium默认不能播放Mp4,所以需要需要改一下源 ...

  4. 从Chrome源码看audio/video流媒体实现一(转)

    现在绝大多数的网站已经从flash播放器转向了浏览器原生的audio/video播放器,浏览器是如何加载和解析多媒体资源的,这对于web开发者来说是一个黑盒,所以很有必要看一下浏览器是怎么实现的,Ch ...

  5. Android学习笔记——从源码看Handler的处理机制

    可能是出于性能的考虑,Android的UI操作是非线程安全的. 也就是说,如果你在一个新开的线程中直接操作UI是会引发异常的. 但是,Android又规定,不要去阻塞UI线程!否则,轻者引起程序卡顿, ...

  6. Android从源码看ListView的重用机制

    不管是android还是iOS,列表视图应该是最复杂的控件了.android中的listview从命名能够看出是个一维数组,而iOS中的tableview则是二维数组.但事实上须要注意的地方是差点儿相 ...

  7. 从微信小程序开发者工具源码看实现原理(四)- - 自适应布局

    从前面从微信小程序开发者工具源码看实现原理(一)- - 小程序架构设计可以知道,小程序大部分是通过web技术进行渲染的,也就是最终通过浏览器的dom tree + cssom来生成渲染树:既然最终是通 ...

  8. 从微信小程序开发者工具源码看实现原理(一)- - 小程序架构设计

    使用微信小程序开发已经很长时间了,对小程序开发已经相当熟练了:但是作为一名对技术有追求的前端开发,仅仅熟练掌握小程序的开发感觉还是不够的,我们应该更进一步的去理解其背后实现的原理以及对应的考量,这可能 ...

  9. Google Chrome 源码下载地址 (Google Chrome Source Code Download)

    1. Google Chrome 源码 SVN 地址:http://src.chromium.org/svn.包含有 Chrome.Gears.Webkit.GCC 等源码以及编译依赖工具.Chrom ...

随机推荐

  1. jQuery方式事件冒泡的2个方法

    方式1:通过  event.stopPropagation(); $("div").click(function (event) { slide.call(this); event ...

  2. spark 文件系统Alluxio(之前名为Tachyon)

    http://www.alluxio.org/documentation/v1.0.0/cn/ http://www.winseliu.com/blog/2016/04/15/alluxio-quic ...

  3. 2014非专业知识学习---be smart

    非专业部分--构建人生 以书籍和网易公开课为主 (1)理财&投资 基金投资相关,好的书籍? (2)哲学总览 <公正>这个看了大半,需要总结归纳.  (必选) 同时结合哲学史,归纳西 ...

  4. Struts拦截器使用

    创建拦截器java程序 package cn.itcast.oa.util; import com.opensymphony.xwork2.ActionInvocation; import com.o ...

  5. (简单) POJ 3268 Silver Cow Party,Dijkstra。

    Description One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1..N is going to atten ...

  6. ios 添加PCH文件

  7. POJ3259负环判定

    题意:有n个顶点,m条边,然后有w个洞,过每个洞的时间为-ti,求是否会时光倒流 分析:就是求是否存在负圈,用Bellman-Floyd判定是否存在负圈即可,注意是无向图,所以路径是双向可达的 #in ...

  8. Codeforces#362

    A题 题意:给定一串数列,t,t+s,t+s+1,t+2s,t+2s+1......问某一个数是否是数列当中的 题意:只需判断(x-t)与(x-t-1)能否整除s即可,注意起始时的判断 #includ ...

  9. 【iScroll源码学习01】准备阶段 - 叶小钗

    [iScroll源码学习01]准备阶段 - 叶小钗 时间 2013-12-29 18:41:00 博客园-原创精华区 原文  http://www.cnblogs.com/yexiaochai/p/3 ...

  10. MapReduce 简单的全文搜索2

    上一个全文搜索实现了模糊查找,这个主要实现了精确查找,就是比如你查找mapreduce is simple那么他就只查找有这个句子的文章,而不是查找有这三个单词的文章. 这个版本需要重写反向索引,因为 ...