Html 鼠标悬停时继续调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18544237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:51:48  来源:igfitidea点击:

Keep calling on a function while mouseover

javascripthtmlcss

提问by Mister Joe

how do I keep calling a function on mouseover while the mouse is hovered over an htmlelement

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

Example:

例子:

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

How can I keep calling the function a while the mouse is hovered over the div instead of having it call the function once.

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

回答by Lathejockey81

Events don't repeat automatically. You can use a timer to repeat the command while the mouse is over, but don't forget to stop the timer at the onmouseout event. You'll need a variable outside of the functions to track the timer so it can be cancelled, which is why we have var repeaterdeclared separately.

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

<script>
  var repeater;

  function a() ...
</script>

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

回答by Charaf JRA

Here is one possible solution using setTimeout(DEMO HERE), it will be repeated every second:

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

HTML CODE:

HTML代码:

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

JS code :

JS代码:

<script>
 document.getElementById('div').onmouseover=function(){a();};

 function a(){

   //some code here

   setTimeout(a,1000);

  }
</script>

回答by MSeifert

As others already mentioned calling a function repeatedly can be achieved using setIntervaland stopping it can be done using clearInterval.

正如其他人已经提到的setInterval那样,可以使用clearInterval.

In case you're looking for a general solution you could use something like this:

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

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

    element.addEventListener('mouseout', function () {
        clearInterval(interval);
    });
}

This starts the interval when the mouse is over the elementand will call the actionfunction every milliseconds. When the mouse leaves the element the repeated action will be stopped (until you hover the element again).

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

Just to show a simple application that counts the accumulated (complete) seconds you hovered an element:

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

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>

When you run the snippet note that it stops counting when you leave the element, but it resumes counting when you hover it again.

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

Maybe important to note that mouseoutcould also be replaced with mouseleaveand similarly for mouseoverand mouseenter. They will behave different if the element you attach the handler to has child elements.

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



Just a note about compatibility:

关于兼容性的说明:

  • addEventListeneris not supported in Internet Explorer 8 and before (see this Q+Afor workarounds).
  • The mouseenterand/or mouseleaveevent are not supported (or supported correctly) in several old browsers. Check the notes about compatibility in case you have to support these (see for example this Q+A).
  • addEventListener不支持 Internet Explorer 8 及更早版本(有关变通方法,请参阅此 Q+A)。
  • mouseenter和/或mouseleave活动,不支持(或正确支持)的几个旧的浏览器。如果您必须支持这些,请检查有关兼容性的说明(例如参见此 Q+A)。

回答by roasstbeef

TRY THIS FIDDLE

试试这个小提琴

http://jsfiddle.net/C4AVg/

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

回答by Lucas Andrade

I think what you're looking for is actually the onmousemoveevent, it's a cleaner way to access the eventobject while you hover some element.

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

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

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

onmousemoveevent is called while you're hoveringthe element, check this example from W3 School.

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

And to understand more about this event, Mozilla docscovers much info about it.

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

回答by public override

//
// 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...
//
//

回答by Nawed Shaikh

You should use setInterval()function here...

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

it also gives you the power to call the function in whatever time interval you desire like: setInterval("a()",1000);here the time is 1/1000 of a second so 1000 means 1 second you can put this setInterval function in any function say b()and call the b()function from the div tag:

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

<div onmouseover="b()">

回答by Yuan Zhaohao

<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>