【问题标题】:How do I make mouseover actions in jQuery continue如何让 jQuery 中的鼠标悬停动作继续
【发布时间】:2013-07-15 14:28:00
【问题描述】:

我正在尝试构建一些在悬停时移动 DIV 框的悬停按钮。我为此使用鼠标悬停,但这只会使 DIV 框移动一次,而我希望它在按钮悬停时继续移动。

这可能吗?

这是代码:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">    </script>
<title>jQuery tests</title>
<style type="text/css">
    .div1{
        position: absolute;
        border-style: solid;
        border-radius: 7px;
        top:50px;
        width: 75px;
        height: 75px;
        z-index: -1;
    }
    .but{
        border-style: dashed;
        padding: 2px;
        margin:2px;
        width: 50px;
        text-align: center;
    }
</style>
</head>
<body>
<div style="width:310; align:center;">
    <div class="but" id="up">Up</div>
    <div class="but" id="left" style="float:left;">Left</div>
    <div class="but" id="right" style="float:left;">Right</div>
    <div class="but" id="down">Down</div>
    <div class="div1"></div>
</div>
<script>

        $('#left').on('mouseover', function(){
                $('.div1').animate({'left':'-=50'},100);
        });
        $('#right').on('mouseover', function(){
                $('.div1').animate({'left':'+=50'},100);
        });
        $('#up').on('mouseover', function(){
                $('.div1').animate({'top':'-=50'},100);
        });
        $('#down').on('mouseover', function(){
                $('.div1').animate({'top':'+=50'},100);
        });

</script>

</body>
</html>

【问题讨论】:

  • 认为您需要查看setinterval 并使用变量来检查您是否使用鼠标在 div 上 (mouseover,mouseout)。 mouseover 只触发一次,所以你不能随意使用它。
  • 这可能对你有帮助 - stackoverflow.com/questions/2331439/…

标签: jquery hover mouseover


【解决方案1】:

使用setInterval 来做!

这是一个 jsFiddle 在右侧悬停时执行此操作:

http://jsfiddle.net/vN2da/

请注意,您需要设置mouseleave 事件来清除间隔。

## 编辑##

我已经更新了 jsFiddle 以在所有方向上进行操作:

http://jsfiddle.net/vN2da/1/

我希望这对你有用。

【讨论】:

    【解决方案2】:

    在动画上使用函数并在动画完成后绑定相同的函数。

    var anim = true;
    function animateAll(dir, ln, speed)
    {
        if(anim)
        {
            var opt = {};
            opt[dir] = ln;
            $('.div1').animate(opt, speed, function(){
                   animateAll(dir,ln, speed)
            });
        }
    }
    
    $('#left').mouseover(function() {
        anim=true;
        animateAll('left','-=50px', 100);
    });
    $('#top').mouseover(function() {
        anim=true;
        animateAll('top','-=50px', 100);
    });
    $('#right').mouseover(function() {
        anim=true;
        animateAll('left','+=50px', 100);
    });
    $('#down').mouseover(function() {
        anim=true;
        animateAll('top','+=50px', 100);
    });
    $('#left, #top, #right, #down').mouseout(function() {
        anim = false;
    });
    

    我的所有方面的新解决方案..

    看看this - Fiddle

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 2011-01-20
      • 1970-01-01
      • 2012-01-23
      • 2011-08-04
      • 2015-09-25
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      相关资源
      最近更新 更多