简体   繁体   中英

css change inside setTimeout doesn't work

The below code inside setTimeout doesn't work whereas same code without setTimeout works perfectly fine

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.

So, you can use the bind method:

$('#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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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