繁体   English   中英

鼠标悬停时继续调用函数

[英]Keep calling on a function while mouseover

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

例子:

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

我怎样才能在鼠标悬停在 div 上的同时继续调用该函数,而不是让它调用该函数一次。

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

<script>
  var repeater;

  function a() ...
</script>

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

这是使用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>

试试这个小提琴

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);
});

正如其他人已经提到的那样,可以使用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; }
 <span id="over">Hover me (at least one second)!</span>

当您运行代码片段时,请注意它会在您离开元素时停止计数,但当您再次悬停它时它会继续计数。

也许重要的是要注意mouseout也可以替换为mouseleave ,类似的用于mouseovermouseenter 如果您将处理程序附加到的元素具有子元素,则它们的行为会有所不同。


关于兼容性的说明:

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

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

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

<div onmouseover="b()">
<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>
//
// 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...
//
//

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

<script>
    function a() {
        "special code hear"
    }
</script>

<div onmousemove( 'a()')>&nbsp;</div>

当您悬停元素时调用onmousemove事件,请查看W3 School 中的此示例

要了解有关此事件的更多信息, Mozilla 文档涵盖了有关它的大量信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM