当用户在输入字段事件中输入内容时,为该字段事件添加动画占位符

Animate placeholder for an input field event when user inputs something there

本文关键字:事件 输入 字段 添加 占位符 动画 用户      更新时间:2023-09-26

我见过这样的演示。

但这是关于创建一个新元素。

parent().append("<span>" + $input.attr('placeholder') + "</span>");

有没有办法在不附加新元素的情况下对占位符在input event上的消失进行动画处理?

$("input[placeholder]").each(function () {
    
    var $input = $(this);
    // wrap the input with a label
    $input.wrap("<label class='placeholder'>");
    // append a span to the label
    $input.parent().append("<span>" + $input.attr('placeholder') + "</span>");
    // and finally remove the placeholder attribute
    $input.attr('placeholder', '');
    
}).keyup(function () {
    
    var $input = $(this);
    // toogle hidden class on span, according to whether there is content or not
    if ($input.val() === "") {
        $input.next("span").removeClass("hidden");
    } else {
        $input.next("span").addClass("hidden");
    }
});
label.placeholder {
    position: relative;
}
label.placeholder span {
    opacity: 1;
    -webkit-transition: opacity 250ms;
    -moz-transition: opacity 250ms;
    -o-transition: opacity 250ms;
    -ms-transition: opacity 250ms;
    transition: opacity 250ms;
    position: absolute;
    left: 5px;
    top: 2px;
    font-size: 12px;
    color: grey;
}
label.placeholder span.hidden {
    opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="the placeholder">

有没有办法在不附加新元素的情况下对占位符在输入事件上的消失进行动画处理?

由于默认浏览器伪元素(即 ::-webkit-input-placeholder/::-moz-placeholder:-ms-input-placeholder)很难跨浏览器设置样式,因此您可以使用:before:after伪元素代替追加的span元素。但是,由于伪元素无法添加到input元素中,因此您仍然需要包装input元素。

更新的示例

伪元素绝对

相对于父元素定位,以便覆盖父元素。伪元素的content值基于包装元素的自定义data-*属性data-placeholder,这是使用contentattr(data-placeholder)实现的。

我还稍微简化了你的jQuery:

$('input[placeholder]').each(function () {
    $(this).wrap('<label class="placeholder" data-placeholder="' + this.placeholder + '">').attr('placeholder', '');
}).on('keyup', function () {
    $(this).parent().toggleClass('hidden', this.value !== '');
});
label.placeholder {
    position: relative;
}
label.placeholder:after {
    content: attr(data-placeholder);
    position: absolute;
    top:0; right: 0;
    bottom: 0; left: 0;
    padding: 2px;
    font-size: 12px;
    color: grey;
    cursor: text;
    transition: opacity 250ms;
}
label.hidden.placeholder:after {
    opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="the placeholder"/>


对于长placeholder值,您还可以添加以下内容:

更新的示例

label.placeholder:after {
    /* .. */
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}