当鼠标静止时,让一个盒子褪色并在鼠标移动时逐渐消失



我一直很难获得此基本代码以正确函数。我已经查找了解决方案,但我想我缺乏实现它们的知识,因为我仍然无法在鼠标静止时使愚蠢的盒子褪色。对此的任何帮助都将不胜感激,这是我的凝结代码:

<!DOCTYPE html>
    <html>
    <head>
        <style>
        #box {
            height: 100px;
            width: 100px;
            background-color: green;
        }
        </style>
        <script>
        var fadeout = null;
        $(document).mousemove(function() {
        $("#box").stop().fadeIn("slow");
        if (fadeout != null) {
            clearTimeout(fadeout);
        }
        fadeout = setTimeout(hide_playlist, 3000);
    });
        function hide_playlist() {
        $("#box").stop().fadeOut("slow");
    }</script>
    <title>Page Title</title>
    </head>
    <body>
    <div id="box"></div>
    <h1>Why wont you work.</h1>
    </body>
    </html>

您应该尝试使用mouseentermouseleave使用不透明的过渡。

这是我的JSFIDDLE示例:https://jsfiddle.net/z19q19yu/

$('#box').mouseenter(function(){
    $(this).css('opacity', '1');
})
$('#box').mouseleave(function(){
    $(this).css('opacity', '0.3');
})

首先,请确保您在脚本之前引用文件中的jQuery。

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

第二,您仅在首页加载上设置超时,因此,当您使用ClearTimeOut清除它时,它将再也不会设置。我让它与这个小调整一起工作:

var fadeout = null;
    $(document).mousemove(function() {
        $("#box").stop().fadeIn("slow");
        if (fadeout != null) {
            clearTimeout(fadeout);
            fadeout = setTimeout(hide_playlist, 3000); //added this line!
        }
        fadeout = setTimeout(hide_playlist, 3000);
    });
    function hide_playlist() {
    $("#box").stop().fadeOut("slow");
    }