【问题标题】:Keep calling on a function while mouseover鼠标悬停时继续调用函数
【发布时间】:2013-08-31 03:36:41
【问题描述】:

当鼠标悬停在 html 元素上时,如何在鼠标悬停时继续调用函数

示例:

<script>
    function a() {
        "special code hear"
    }
</script>
<div onmouseover( 'a()')>&nbsp;</div>

如何在鼠标悬停在 div 上而不是让它调用一次函数时继续调用该函数。

【问题讨论】:

  • @FaceOfJock 一定是setInterval()
  • 您可以在悬停时使用 setInverval 并在悬停时使用 cleartimeout 来执行此操作
  • @DipeshParmar 他希望它执行一次以上,x 秒后不执行
  • @FaceOfJock @FaceOfJock settimeout 只会在定义的时间后工作一次...而setInterval 在指定的时间后继续调用函数...
  • @FaceOfJock Read Here

标签: javascript html css


【解决方案1】:

事件不会自动重复。您可以使用计时器在鼠标悬停时重复命令,但不要忘记在 onmouseout 事件时停止计时器。您需要在函数之外使用一个变量来跟踪计时器,以便将其取消,这就是我们单独声明 var repeater 的原因。

<script>
  var repeater;

  function a() ...
</script>

<div onmouseover="repeater=setInterval(a(), 100);" onmouseout="clearInterval(repeater);"></div>

【讨论】:

    【解决方案2】:

    这是使用setTimeout (DEMO HERE) 的一种可能解决方案,它将每秒重复一次:

    HTML 代码:

    <div id='div'>test</div>
    

    JS代码:

    <script>
     document.getElementById('div').onmouseover=function(){a();};
    
     function a(){
    
       //some code here
    
       setTimeout(a,1000);
    
      }
    </script>
    

    【讨论】:

    • 也可以将超时行替换为:setTimeout("a", 1000);
    【解决方案3】:

    试试这个小提琴

    http://jsfiddle.net/C4AVg/

    var pee = '';
    $('#poop').mouseover(function(){
    
                  pee =  setInterval(function() {
          // Do something every 5 seconds
                       alert('hi');
    }, 1000);
    });
        $('#poop').mouseout(function() {
            clearInterval(pee);
    });
    

    【讨论】:

    • 他没有使用 jQuery
    【解决方案4】:

    正如其他人已经提到的那样,重复调用一个函数可以使用setInterval 来实现,并且可以使用clearInterval 来停止它。

    如果您正在寻找通用解决方案,您可以使用以下方法:

    function repeatWhileMouseOver(element, action, milliseconds) {
        var interval = null;
        element.addEventListener('mouseover', function () {
            interval = setInterval(action, milliseconds);
        });
    
        element.addEventListener('mouseout', function () {
            clearInterval(interval);
        });
    }
    

    这会在鼠标悬停在element 上时开始间隔,并会在每个milliseconds 调用action 函数。当鼠标离开元素时,重复的动作将停止(直到您再次悬停该元素)。

    只是为了展示一个简单的应用程序,它计算您悬停一个元素的累积(完整)秒数:

    function repeatWhileMouseOver(element, action, time) {
        var interval = null;
        element.addEventListener('mouseover', function() {
            interval = setInterval(action, time);
        });
    
        element.addEventListener('mouseout', function() {
            clearInterval(interval);
        });
    }
    
    var counter = 1;
    function count() {
        console.log(counter++);
    }
    repeatWhileMouseOver(document.getElementById('over'), count, 1000);
    #over {
      border: 1px solid black;
    }
    &lt;span id="over"&gt;Hover me (at least one second)!&lt;/span&gt;

    当您运行 sn-p 时请注意,当您离开该元素时它会停止计数,但当您再次悬停它时它会恢复计数。

    可能需要注意,mouseout 也可以替换为 mouseleavemouseovermouseenter 也是如此。如果您附加处理程序的元素具有子元素,它们的行为会有所不同。


    只是关于兼容性的说明:

    • Internet Explorer 8 及之前的版本不支持addEventListener(有关解决方法,请参阅this Q+A)。
    • 几个旧浏览器不支持(或正确支持)mouseenter 和/或mouseleave 事件。如果您必须支持这些,请查看有关兼容性的说明(例如参见 this Q+A)。

    【讨论】:

      【解决方案5】:
      <script type="text/javascript">
      var tId = null,
          time = 100;
      $( '#test' ).hover(
          function( event ) {
              tId = setTimeout( function() {
      
              }, time);
          },
          function( event ) {
              clearTimeout( tId );
          }
      )
      </script>
      <div id="test">test</div>
      

      【讨论】:

        【解决方案6】:

        你应该在这里使用setInterval()函数...

        它还使您能够在所需的任何时间间隔内调用该函数 喜欢:setInterval("a()",1000); 这里时间是 1/1000 秒,所以 1000 表示 1 秒 您可以将此 setInterval 函数放在任何函数中,例如 b() 并从 div 标签调用 b() 函数:

        <div onmouseover="b()">
        

        【讨论】:

        • 对不起,我是用手机打字,所以格式不对
        【解决方案7】:
        //
        // try the timer factory
        //
        function timer ( callbacks, delay, fireNTimes ) {
        
            timer._cb ||
            ( timer._cb = function () { return true; } );
        
            return (function ( callbacks, delay, fireNTimes ) {
        
                var
                    un,
                    timerState = {
                        'current-count' : 0,
                        'delay'         : Math.abs( parseFloat( delay ) )    || 1000,
                        'repeat-count'  : Math.abs( parseInt( fireNTimes ) ) || Number.POSITIVE_INFINITY,
                        'running'       : false,
                        'interval'      : un
                    },
        
                    callback = {
                        onTimer: callbacks.onTimer || timer._cb,
                        onStart: callbacks.onStart || timer._cb,
                        onStop : callbacks.onStop  || timer._cb,
                        onEnd  : callbacks.onEnd   || timer._cb
                    };
        
                return {
        
                    ctx: this,
        
                    startargs: [],
        
                    start: function ( /* callbacks_context, ...params */ ) {
        
                        var
                            that = this,
                            args = Array.prototype.slice.call( arguments, 1 );
        
                        ( arguments[0] !== un ) && ( this.ctx = arguments[0] );
                        ( args.length  != 0 )   && ( this.startargs = args   );
        
                        this.running() || (
                            timerState.running = true,
                            callback.onStart.apply( this.ctx, this.startargs ),
                            timerState['current-count'] += 1,
                            callback.onTimer.apply( this.ctx, this.startargs ),
                            ( timerState['current-count'] == timerState['repeat-count'] ) &&
                              (
                                callback.onEnd.apply( this.ctx, this.startargs ),
                                ( timerState["current-count"] = +( timerState.running = false ) ), true
                              ) ||
                            ( timerState.interval =
                                window.setInterval( function () {
                                        timerState['current-count'] += 1;
                                        callback.onTimer.apply( that.ctx, that.startargs );
                                        ( timerState['current-count'] == timerState['repeat-count'] ) &&
                                        that.reset() &&
                                        callback.onEnd.apply( that.ctx, that.startargs );
                                    }, timerState.delay
                                )
                            )
                        );
                        return this;
                    },
                    stop: function () {
        
                        this.running() &&
                        (
                          window.clearInterval( timerState.interval ),
                          timerState.interval = un,
                          timerState.running  = false,
                          callback.onStop.apply( this.ctx, this.startargs )
                        );
                        return this;
                    },
                    reset: function () {
                        return this.running() &&
                        ( ! ( timerState["current-count"] = +( timerState.running = false ) ) ) &&
                        ( window.clearInterval( timerState.interval ), true ) &&
                        ( ( timerState.interval = un ), this );
                    },
                    currentCount: function () {
                        return timerState['current-count'];
                    },
                    delay: function () {
                        return timerState.delay;
                    },
                    repeatCount: function () {
                        return timerState['repeat-count'];
                    },
                    running: function () {
                        return timerState.running;
                    }
                };
        
            })( callbacks, delay, fireNTimes );
        
        }
        
        var
            tm = timer(
                       {
                        onStart : function () { console.log( 'start:', 'this === ', this, arguments ); },
                        onTimer : function () { console.log( 'timer:', 'this === ', this, arguments ); },
                        onEnd   : function () { console.log( 'done:',  'this === ', this, arguments ); },
                        onStop  : function () { console.log( 'pause:', 'this === ', this, arguments ); }
                       },
                       2000
                 ),
            el = document.getElementById('btn1'),
            o  = { p1:'info' };
        
        el.onmouseover = function () { tm.start( el, o ); };
        el.onmouseout  = function () { tm.stop(); };
        
        //
        //
        //  start: this === <button id="btn1"> [Object { p1="info"}]
        //  timer: this === <button id="btn1"> [Object { p1="info"}]
        //  timer: this === <button id="btn1"> [Object { p1="info"}]
        //  timer: this === <button id="btn1"> [Object { p1="info"}]
        //  pause: this === <button id="btn1"> [Object { p1="info"}]
        //
        //    etc...
        //
        //
        

        【讨论】:

          【解决方案8】:

          我认为您正在寻找的实际上是 onmousemove 事件,它是在悬停某些元素时访问 event 对象的一种更简洁的方式。

          <script>
              function a() {
                  "special code hear"
              }
          </script>
          
          <div onmousemove( 'a()')>&nbsp;</div>
          

          onmousemove 事件在您悬停元素时被调用,检查this example from W3 School

          要了解有关此事件的更多信息,Mozilla docs 涵盖了有关它的许多信息。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-26
            • 2012-07-27
            • 2012-01-23
            • 2015-09-25
            • 2021-11-18
            • 1970-01-01
            • 2016-06-15
            • 1970-01-01
            相关资源
            最近更新 更多