setTimeout不能与onmouseout一起工作

setTimeout not working with onmouseout

本文关键字:一起 工作 onmouseout 不能 setTimeout      更新时间:2023-09-26

首先是有问题的代码行:

<a onmouseover="hoverDisplay(this)" onmouseout="setTimeout(unHoverDisplay(), 3000);" href="http://rabbit.jpg">
            Rabbit
        </a><br>

基本上,我希望图像加载并出现当我悬停在链接上,我希望它消失一段时间后当我悬停在链接。方法:

hoverDisplay(this)
unHoverDisplay()

分别显示和删除图像,但当我试图延迟unHoverDisplay()时,它不起作用;鼠标一离开链接,图像就消失了。

我试过在setTimeout后添加和删除分号(不确定分号是否必要),我也试过延迟hoverDisplay函数,这不起作用。除了延迟问题,这两个函数都能正常工作。

这似乎是一个简单的问题,但我不知道我做错了什么。帮助是值得感激的。谢谢。

不确定这是否必要,但以下是这两个函数的实现:

//Display image for link that you hover over
            var address; //Address of image
            var toBeDisplayed; //Declaring img object
            var maxHeight=screen.height;
            var maxWidth=screen.width;
            var invisible=document.getElementById("invisible"); //the div in which the image is contained
            function hoverDisplay(imageLink)
            {
                address=imageLink.getAttribute("href"); //get address
                toBeDisplayed=document.createElement("img"); //create img                           
                toBeDisplayed.setAttribute("src", address); //give img the address
                //Resize img if it doesnt fit on the screen
                if(toBeDisplayed.height > maxHeight)
                {
                    toBeDisplayed.style.height="" + maxHeight + "px";
                }
                else if(toBeDisplayed.width > maxWidth)
                {
                    toBeDisplayed.style.width="" + maxWidth + "px";
                }
                invisible.appendChild(toBeDisplayed); //display image by adding it as a child to a div
                invisible.style.visibility="visible"; //make div visible
                toBeDisplayed.style.border="solid yellow 5px";
            }
            //Remove image once you hover out of the link
            function unHoverDisplay()
            {
                //Removes all children of the div
                while(invisible.firstChild)
                {
                    invisible.removeChild(invisible.firstChild); //remove img by removing it as a child
                }
                invisible.style.visibility="hidden";
            }

麻烦的是,unHoverDisplay后的括号在你的第一个参数setTimeout导致unHoverDisplay立即执行。您只需通过不带括号的标识符传递函数:

onmouseout="setTimeout(unHoverDisplay, 3000);"

将函数作为参数传递给setTimeout,而不是调用它。因此,不需要在函数名后面加上括号,所需要的只是函数名本身。

onmouseout = "setTimeout(unHoverDisplay, 3000);"