我正在尝试创建一个联系表单,用户点击输入/文本区域,标 checkout 现在输入/文本区域的顶部,如下所示:
the correct outcome
我已经创建了 HTML 和 CSS,但我的问题是 Javascript(Jquery)。每次用户尝试在其中一个输入上键入时,所有标签都会出现,这不是我想要做的。
JS:
$(document).ready(function() {
// Test for placeholder support
$.support.placeholder = (function(){
var i = document.createElement('input');
return 'placeholder' in i;
})();
// Hide labels by default if placeholders are supported
if($.support.placeholder) {
$('.form-label').each(function(){
$(this).addClass('js-hide-label');
});
// Code for adding/removing classes here
$('.form-group').find('input, textarea').on('keyup blur focus', function(e){
// Cache our selectors
var $this = $(this),
$parent = $this.parent().find("label");
if (e.type == 'keyup') {
if( $this.val() == '' ) {
$('label').addClass('js-hide-label');
} else {
$('label').removeClass('js-hide-label');
}
}
else if (e.type == 'blur') {
if( $this.val() == '' ) {
$('label').addClass('js-hide-label');
}
else {
$('label').removeClass('js-hide-label').addClass('js-unhighlight-label');
}
}
else if (e.type == 'focus') {
if( $this.val() !== '' ) {
$('label').removeClass('js-unhighlight-label');
}
}
});
}
});
最佳答案
我进行了 2 处更改并使其正常工作。正如 Taplar 在他的评论中提到的那样,您找到了所有标签。我更新了该行以找到父 div 的 prev
元素,它是 form-group
的标签。我还更改了您的 if else 逻辑以使用您正在缓存的 $parent 元素(现在是标签元素)
// Code for adding/removing classes here
$('.form-group').find('input, textarea').on('keyup blur focus', function(e){
// Cache our selectors
var $this = $(this),
// fixed this line to find prev()
$parent = $(this).parent().prev();
// update all of the statements to use $parent(link element)
if (e.type == 'keyup') {
if( $this.val() == '' ) {
$parent.addClass('js-hide-label');
} else {
$parent.removeClass('js-hide-label');
}
}
else if (e.type == 'blur') {
if( $this.val() == '' ) {
$parent.addClass('js-hide-label');
}
else {
$parent.removeClass('js-hide-label').addClass('js-unhighlight-label');
}
}
else if (e.type == 'focus') {
if( $this.val() !== '' ) {
$parent.removeClass('js-unhighlight-label');
}
}
});
关于javascript - 尝试使用父函数添加/删除 css 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48081346/