javascript - 文本输入中的打字机效果在 Firefox 中不起作用

标签 javascript jquery html settimeout cleartimeout

当用户将鼠标悬停在输入上时,此代码会在输入中产生打字机动画效果,它会为占位符文本设置动画。当用户离开时,我希望动画停止并且输入返回其原始状态。

$(function() {

    var sppInput,
        sppInputName = $('#spp-input-name'),
        sppInputNamePlace = sppInputName.attr('placeholder');

    // Typewriter Effect
    function sppInputStart(elm, n, text) {
        if (n < (text.length)) {
            $(elm).attr('placeholder', text.substring(0, n + 1));
            n++;
            sppInput = setTimeout(function () {
                sppInputStart(elm, n, text);
            }, 80);
        }
    }
    function sppInputStop(elm, place) {
        clearTimeout(sppInput);
        $(elm).attr('placeholder', place);
    }

    // Typewriter Effect for Name
    sppInputName.mouseover(function () {
        sppInputStart(this, 0, sppInputName.data('typewriter'));
    });
    sppInputName.mouseout(function () {
        sppInputStop(this, sppInputNamePlace);
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Name" data-typewriter="Insert the Name" type="text" id="spp-input-name" name="name" required>

此代码适用于所有浏览器(包括 IE),但不适用于 firefox。

为什么?

最佳答案

看起来像更改 placeholder 值会重新触发 mouseover 事件

有效的“技巧”:

$(document).ready(function() {

    var sppInput,
        sppInputName = $('#spp-input-name'),
        sppInputNamePlace = sppInputName.attr('placeholder');

    // Typewriter Effect
    function sppInputStart(elm, n, text) {
        if (n < (text.length)) {
            $(elm).attr('placeholder', text.substring(0, n + 1));
            n++;
            sppInput = setTimeout(function() {
                sppInputStart(elm, n, text);
            }, 80);
        }
    }

    function sppInputStop(elm, place) {
        clearTimeout(sppInput);
        $(elm).attr('placeholder', place);
    }

    // Typewriter Effect for Name
    sppInputName.mouseover(function() {
        // hack
        if ($(this).data('flag') != '1') {
            $(this).data('flag', '1');
            sppInputStart(this, 0, sppInputName.data('typewriter'));
        }
    });
    sppInputName.mouseout(function() {
        // hack
        $(this).data('flag', '0');
        sppInputStop(this, sppInputNamePlace);
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Name" data-typewriter="Insert the Name" type="text" id="spp-input-name" name="name" required>

关于javascript - 文本输入中的打字机效果在 Firefox 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48184316/

相关文章:

javascript - Angularjs 路由与 django 的 url

javascript - 固定导航下方的 HTML 内容

jquery - 只获取文件的一部分

jquery - 使用 jQuery .filter() 按行过滤表中不包括特定列的文本

html - 移动设备上不显示滚动条

javascript - 将文本从 HTML 转换为 Javascript 作为输入更改 ID 的函数

javascript - 在组件端处理 Apollo 错误

javascript - Angular 方向清晰场

c# - 将动态生成的 javascript 保存到 html 文件中或将此内容放入字符串中并发送给 Controller

Javascript 和 HTML - 从 SPAN 和选择中获取值(value)