在jQuery中停止将鼠标悬停在3秒钟后如何保持有效? jsFiddle

问题描述 投票:0回答:3

此代码的作用是,当您将鼠标悬停在列表中的某个项目上时,它将变为红色,并在下面显示另一个列表。如果您不再将鼠标悬停在任何元素上,则目标是将您悬停的最新事物在清除之前停留3秒钟。

$('#stockList li').hover(
            function () {
                    $(this).css({ color: 'red' }); //mouseover
                    if ($(this).text() == symbol) {

                        $('#stockInfo').append('<div><ol><li>' + "Company = " + company + '</li><br/><li>' + "Market = " + market + '</li><br/><li>' + "Sector = " + sector + '</li><br/><li>' + "Price = " + price + '</li><br/><li>' + "Year Range = " + low + " " + high + '</li><br/><li>' + "Dividend = " + amount + " " + yieldx + " " + frequency + '</li></ol><br/></div>');
                    }
                },

            function () {
                $(this).css({ color: 'navy' }); // mouseout
                $('#stockInfo').empty();
            }
        );
jquery jquery-hover
3个回答
0
投票

只需添加delay

$(this).delay(3000).css({ color: 'navy' }); // mouseout
$('#stockInfo').empty();

请记住,javascript时间以毫秒为单位,因此3秒是javascript中的3000毫秒。

请参阅有关延迟here的jQuery文档。


0
投票

悬停效果将保持不变,直到您将鼠标光标移出元素为止

jsFiddle

您可以执行以下操作:

var timeout;
    $('#stockList li').hover(
           function () {
              clearTimeout(timeout);// this will take care if user re-hover over the element
              $(this).css({ color: 'red' }); //mouseover
                  if ($(this).text() == symbol) {        
                     $('#stockInfo').append('<div><ol><li>' + "Company = " + company + '</li><br/><li>' + "Market = " + market + '</li><br/><li>' + "Sector = " + sector + '</li><br/><li>' + "Price = " + price + '</li><br/><li>' + "Year Range = " + low + " " + high + '</li><br/><li>' + "Dividend = " + amount + " " + yieldx + " " + frequency + '</li></ol><br/></div>');
                        }
                    },

                function () {
               timeout=  setTimeout(function(){
                    $('#stockList li').css({ color: 'navy' }); // mouseout
                    $('#stockInfo').empty();
                  },3000);
                }
            );

0
投票
$('#stockList li').hover(
            function () {
                    $(this).css({ color: 'red' }); //mouseover
                    if ($(this).text() == symbol) {

                        $('#stockInfo').append('<div><ol><li>' + "Company = " + company + '</li><br/><li>' + "Market = " + market + '</li><br/><li>' + "Sector = " + sector + '</li><br/><li>' + "Price = " + price + '</li><br/><li>' + "Year Range = " + low + " " + high + '</li><br/><li>' + "Dividend = " + amount + " " + yieldx + " " + frequency + '</li></ol><br/></div>');
                    }
                },

            function () {
                setTimeOut(function(){
                    $(this).css({ color: 'navy' }); // mouseout
                    $('#stockInfo').children('div').remove();
                },3000); // Disappear after 3000 ms or 3 seconds
            }
);
© www.soinside.com 2019 - 2024. All rights reserved.