简体   繁体   中英

jQueryUI animate(color) doesn't work

I want to animate background color of input element, but it doesn't works :(

JavaScript (when submit):

function sendImage() {
    formularz = $('form#sendImage');
    autor = formularz.children('input[name=autor]');

    if (autor.val().length < 1 || autor.val().length > 20) {
        console.log('start');
        autor.animate({
            backgroundColor: 'red',
            width: '100px',
        }, 3000, function() {
            console.log('end');
        });
    }
}

jQuery liblaries:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<link rel="stylesheet" href="jquery-ui/jquery-ui.min.css">
<script src="jquery-ui/external/jquery/jquery.js"></script>
<script src="jquery-ui/jquery-ui.min.js"></script>
<!-- I tried also this -->
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

In JS function works well - logs in console are shown, width of element too is changing, but background color not and it do not show any errors in console.

Any suggestions?

jQuery cannot animate background colours by default. You have two options, first you could use a third party plugin. Secondly, you can use CSS. The latter is preferable. Here's how to do it by setting the transition CSS rule on the element and then just adding the class in your jQuery code.

input {
    transition: all 3s;
}
input.error {
    background-color: red;
}
function sendImage() {
    var $formularz = $('form#sendImage');
    var $autor = $formularz.children('input[name=autor]');

    if ($autor.val().length < 1 || $autor.val().length > 20) {
        $autor.addClass('error');
    }
}

Working example

I am pretty sure in Javascript you need to indicate you are adding style to an element via its id. So if you set an element's Id to be autor it would work using the following in your if statement:

document.getElementById('autor').style.background-color="red";

Rory McCrossan, I tested your recommendations and 'backgroundColor' worked well, but later i wanted to check again the backgoundColor and it also works...

So I don't know what was wrong. Mayby some typo or I forgot about somethink. Sorry for the confusion.

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