当鼠标静止时让盒子淡出然后当鼠标移动时淡入淡出

时间:2017-02-24 21:40:44

标签: javascript jquery html css

我一直无法让这个基本代码正常运行。我已经找到了解决方案,但我认为我缺乏必要的知识来实现​​它们,因为当鼠标静止时,我仍然无法让愚蠢的盒子褪色。任何有关这方面的帮助将不胜感激,这是我的简明代码:

<!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>

2 个答案:

答案 0 :(得分:0)

您应该尝试使用mouseentermouseleave进行不透明度转换。

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

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

答案 1 :(得分:0)

首先,请确保在脚本之前在文件中引用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");
    }