简体   繁体   English

setTimeout中的CSS更改不起作用

[英]css change inside setTimeout doesn't work

The below code inside setTimeout doesn't work whereas same code without setTimeout works perfectly fine setTimeout中的以下代码无法正常工作,而没有setTimeout的相同代码则可以正常工作

var size_disabled_input = 0;

$('#txtUSLead , #txtmy').on("mouseover", function () {
size_disabled_input = $(this).css('width');
if ((this.value.length) > 8) 
{
$(this).css('cssText', 'width: ' + ((this.value.length + 1) * 7) + 'px !important');
}
});

$('#txtUSLead, #txtmy').on("mouseout", function () {
setTimeout(function (){
$(this).css('cssText', 'width: ' + size_disabled_input + 'px !important');
}, 2000);
})

Within the setTimeout function this will not refer to the button that you are in. setTimeout函数中, this将不引用您所在的按钮。

So, you can use the bind method: 因此,您可以使用bind方法:

$('#txtUSLead, #txtmy').on("mouseout", function () {
    setTimeout(function () {
        $(this).css('cssText', 'width: ' + size_disabled_input + 'px !important');
    }.bind(this), 2000);
})

Or, use a variable to store the this value: 或者,使用变量存储此值:

$('#txtUSLead, #txtmy').on("mouseout", function () {
    var that = $(this);
    setTimeout(function () {
        that.css('cssText', 'width: ' + size_disabled_input + 'px !important');
    }, 2000);
})

Or, you can use the proxy() method in jQuery: 或者,您可以在jQuery中使用proxy()方法:

$('#txtUSLead, #txtmy').on("mouseout", function () {
    setTimeout($.proxy(function() {
        $(this).css('cssText', 'width: ' + size_disabled_input + 'px !important');
    }, this), 2000);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM