我正在尝试减少“聚焦”和“聚焦”代码中的冗余代码。本质上,我添加/删除一个类取决于我是否专注于我的网页上的输入。
我已经尝试过使用focus()方法而不是focusin / focusout方法。我也尝试过toggleClass()。
// On focus, remove the class of reduce and add the class of expand
$('input[type="text"]').on('focusin', function(){
$(this).removeClass('reduce');
$(this).addClass('expand');
});
// On focus out, add class reduce and remove class expand
$('input[type="text"]').on('focusout', function () {
$(this).addClass('reduce');
$(this).removeClass('expand');
});目前它工作正常,但我只想减少冗余代码。
发布于 2019-04-16 02:23:17
不是很短,但是如果你真的需要减少代码,这对你来说可能是可行的:
$('input[type="text"]').on('focusin focusout', function(ev){
var isFocusIn = ev.type === 'focusin';
$(this).toggleClass('reduce', !isFocusIn).toggleClass('expand', isFocusIn);
});发布于 2019-04-16 02:15:58
现在唯一“多余”的部分是$(this)部分,因为您可以像下面这样链接这些jQuery调用:
// On focus, remove the class of reduce and add the class of expand
$('input[type="text"]').on('focusin', function(){
$(this).removeClass('reduce').addClass('expand');
});
// On focus out, add class reduce and remove class expand
$('input[type="text"]').on('focusout', function () {
$(this).addClass('reduce').removeClass('expand');
});编辑:请注意
// On focus, remove the class of reduce and add the class of expand
$('input[type="text"]').focus(function(){
$(this).removeClass('reduce').addClass('expand');
});
// On focus out, add class reduce and remove class expand
$('input[type="text"]').blur(function () {
$(this).addClass('reduce').removeClass('expand');
});这可能是一个更好的选择,基于this selected answer,用于将事件冒泡到子节点,而不是jQuerys API.Focus/.blur
发布于 2019-04-16 02:20:32
您将在两个不同的事件上触发您的代码,因此我唯一要做的重构是
$('input[type="text"]').on('focusin', function(){
// On focus, remove the class of reduce and add the class of expand
$(this).toggleClass('expand reduce');
}).on('focusout', function () {
// On focus out, add class reduce and remove class expand
$(this).toggleClass('reduce expand');
});https://stackoverflow.com/questions/55695046
复制相似问题