gpt4 book ai didi

javascript - 当用户在那里输入内容时为输入字段事件设置动画占位符

转载 作者:太空狗 更新时间:2023-10-29 12:33:38 24 4
gpt4 key购买 nike

我看过类似 this. 的演示

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

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

有没有一种方法可以让占位符在 input 事件 上消失而无需附加新元素?

$("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">

最佳答案

Is there a way to animate placeholder's disappear on input event without appending a new element?

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

Updated Example

伪元素相对于父元素绝对相对定位,以便覆盖父元素。伪元素的 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 值,您还可以添加以下内容:

Updated Example

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

关于javascript - 当用户在那里输入内容时为输入字段事件设置动画占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29052005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com