为什么这两个事件只应该运行一次才会重复触发?

时间:2013-10-03 12:16:20

标签: jquery events triggers repeat

我已经写了下面的代码,当moused在另一个div上时,它应该显示一个div,代码可以工作但是,事件会被反复触发,为什么会这样?

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <style type="text/css">
            #my-div {
                width: 100px;
                height: 100px;
                background-color: red;
            }
            .tooltip {
                width: 200px;
                height: 200px;
                background-color: red;
                display: none;
            }
        </style>
        <script src="jquery.min.js"></script>
    </head>

    <body>
        <div id="my-div"></div>
        <div class="tooltip"></div>
        <script type="text/javascript">
                    $('#my-div').on('mouseover', function() {
                        $('.tooltip').fadeIn(300);
                    });
                    $('#my-div').on('mouseleave', function() {
                        $('.tooltip').fadeOut(300);
                    });

        </script>
    </body>
</html>

3 个答案:

答案 0 :(得分:1)

您应该使用mouseenter代替mouseover,因为当您将鼠标移动到目标中时,mouseover始终会触发。

要获得更多信息,您应该添加stop()以停止fadeOut()fadeIn()动画触发,就像用户快速移入和移出鼠标一样。

$('#my-div').on('mouseenter', function() {
   $('.tooltip').stop().fadeIn(300);
});
$('#my-div').on('mouseleave', function() {
   $('.tooltip').stop().fadeOut(300);
});

答案 1 :(得分:0)

我发现,问题是什么,我使用Coda,它似乎有奇怪的错误,我在所有其他浏览器上尝试过,它运行正常。我编写了这段代码,它似乎在主流浏览器上运行良好,但由于某些原因Coda拒绝正确运行它:

        function Tooltip() {

            this.showToolTip = function() {
                $(this.element).on('mouseenter', function(event) {
                    event.preventDefault();
                    $(that.tooltip).stop().fadeIn(300);
                });
            };

            this.hideToolTip = function() {
                $(this.element).on('mouseleave', function(event) {
                    event.preventDefault();
                    $(that.tooltip).stop().fadeOut(300);
                });
            };

            this.element = arguments[0];
            this.tooltip = arguments[1];
            var that = this;
        }

答案 2 :(得分:0)

请注意,当鼠标进入或离开(偶然)相关标签或其中一个后代时,会触发鼠标悬停和鼠标移动

你不会在你的例子中看到它,因为工具提示已经消失了.. 试试这个..

$('#my-div').on('mouseover', function() {
    $('body').append('<span>one more time </span>');
    $('.tooltip').fadeIn(300);
});

小提琴here