首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >"Focusin / Focusout“简化jQuery代码

"Focusin / Focusout“简化jQuery代码
EN

Stack Overflow用户
提问于 2019-04-16 02:12:42
回答 3查看 37关注 0票数 0

我正在尝试减少“聚焦”和“聚焦”代码中的冗余代码。本质上,我添加/删除一个类取决于我是否专注于我的网页上的输入。

我已经尝试过使用focus()方法而不是focusin / focusout方法。我也尝试过toggleClass()。

代码语言:javascript
复制
// 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');
});

目前它工作正常,但我只想减少冗余代码。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-04-16 02:23:17

不是很短,但是如果你真的需要减少代码,这对你来说可能是可行的:

代码语言:javascript
复制
$('input[type="text"]').on('focusin focusout', function(ev){
    var isFocusIn = ev.type === 'focusin';
    $(this).toggleClass('reduce', !isFocusIn).toggleClass('expand', isFocusIn);
});
票数 0
EN

Stack Overflow用户

发布于 2019-04-16 02:15:58

现在唯一“多余”的部分是$(this)部分,因为您可以像下面这样链接这些jQuery调用:

代码语言:javascript
复制
// 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');
});

编辑:请注意

代码语言:javascript
复制
// 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

票数 0
EN

Stack Overflow用户

发布于 2019-04-16 02:20:32

您将在两个不同的事件上触发您的代码,因此我唯一要做的重构是

代码语言:javascript
复制
$('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');    
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55695046

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档