即使类名不存在,Javascript事件仍然会触发

有人可以向我解释当一个事件的目标名称不存在时,事件会如何触发。

(function ($) { var config = {}; $(document).ready(function () { var wi = $(window).width(); if ( wi > 768 ) { $('body').addClass('dosomething'); } else { $('body').removeClass('dosomething'); } $(window).resize(function() { var wi = $(window).width(); console.log(wi); if ( wi > 768 ) { $('body').addClass('dosomething'); } else { $('body').removeClass('dosomething'); } var $container = $('.email-signup__wrap'), $cHeight = $('.email-signup').outerHeight(); // $('.dosomething .email-signup__wrap').on('mouseenter mouseleave', function(ev) { $('body').on('mouseenter mouseleave', '.dosomething .email-signup__wrap' , function(ev) { var $this = $(this); if ( ev.type === 'mouseenter' ) { TweenMax.to($container, .4, { ease: Power2.easeOut, css:{ overflow: 'visible', position: 'absolute', top: -$cHeight } }); } else { TweenMax.to($container, .4, { ease: Power2.easeOut, css:{ position: 'relative', top: 0 }, onComplete: hide }); function hide(){ $container.css('overflow', 'hidden'); } $("div.mce_inline_error").remove(); } }); }); }); })( jQuery ); 

我已经有点过分了,将dosomething类添加到每个选择器,以防止事件在768px以下的屏幕尺寸上触发。

基本上,用户将鼠标hover在页脚栏上,并且从canvas上弹出联系人表单,但是在较小的屏幕/移动设备上,它在页面内容的基础上保持静态。

我知道这是基本的代码,但是,我一直试图让它工作好几天,我正忙着寻找一个解决方案。

我不是在做完工作,媒体查询等等……我真的想要了解这一点,这是为了我自己的理智。

最终的工作解决方案

  (function ($) { var config = {}; $(document).ready(function () { $(window).on("resize", function () { resizeWindow(); }).trigger("resize"); var $container = $('.email-signup__wrap'), $cHeight = $('.email-signup').outerHeight(); $(document).on({ mouseenter: function() { TweenMax.to($container, .4, { ease: Power2.easeOut, css:{ overflow: 'visible', position: 'absolute', top: -$cHeight } }); }, mouseleave: function() { TweenMax.to($container, .4, { ease: Power2.easeOut, css:{ position: 'relative', top: 0 }, onComplete: hide }); function hide(){ $container.css('overflow', 'hidden'); } $("div.mce_inline_error").remove(); } }, ".dosomething .email-signup__wrap"); }); function resizeWindow() { config.wWidth = $(window).width(); if ( config.wWidth > 768 ) { $('body').addClass('dosomething'); } else { $('body').removeClass('dosomething'); } } })( jQuery ); 

在jquery中使用event delegation 。 你动态添加类.dosomething

 $('body').on('mouseenter mouseleave', '.dosomething .email-signup__wrap' , function(ev) {