Jquery animate background color не работает

jQuery Animate не работает со свойством background-color

Я играл с функцией jQuery .animate() и попытался изменить background-color одного из div в зависимости от количества пикселей, прокручиваемых пользователем. К моему удивлению, это не сработало. Вместо этого я попытался использовать функцию .css() , и она работала хорошо. Пожалуйста, обратитесь к ссылке jsFiddle внизу.

Может ли кто-нибудь объяснить мне, почему это происходит?

5 ответов

Метод .animate () позволяет нам создавать анимационные эффекты для любого числового свойства CSS .

Свойства и значения анимации

Все анимированные свойства должны быть анимированы в одно числовое значение, за исключением случаев, указанных ниже; большинство нечисловых свойств нельзя анимировать с использованием базовых функций jQuery (например, width , height или left можно анимировать , но <> не может быть , если не используется плагин jQuery.Color)

Цвет фона не является числовым свойством, поэтому его нельзя анимировать с помощью .animate() .

Просто дополнение к существующим ответам: если вы не хотите использовать для этого пользовательский интерфейс jQuery, вы можете использовать этот плагин jQuery (только 2,7 КБ):

Вы можете скачать jquery.animate-colors.js или jquery.animate-colors.min.js с веб-сайта проекта или добавить его из CDN:

После включения вы можете использовать цветную анимацию следующим образом:

Вы можете анимировать backgroundColor только с помощью jQueryUI. Если вы не хотите использовать jQueryUI, вам нужно просто изменить класс и сделать анимацию в CSS с использованием переходов.

Если вы хотите animate background-color свойство, вам нужно включить << X2>> или добавьте этот плагин:

jQuery UI объединяет плагины jQuery Color, которые предоставляют цветную анимацию, а также множество вспомогательных функций для работы с цветами.

Вы также можете анимировать цвет фона с помощью jQuery, но не с помощью метода animate (), как вы заметили, метод css подойдет.

Поскольку это очень просто, не включайте в код другую библиотеку, избавьте себя от http-запросов и просто сделайте это с простым JS.

Источник

JQuery анимированный цвет фона не работает

Я хочу изменить цвет фона ‘exampleDiv’ с исходного белого фона на то, когда я вызываю приведенный ниже код для немедленного изменения желтого фона, а затем постепенно возвращаюсь к исходному белому фону.

Однако этот код не работает.

У меня есть только ядро ​​JQuery и пользовательский интерфейс JQuery, связанные с моей веб-страницей.

Почему код выше не работает?

8 ответов

У меня был разный успех с animate , но я обнаружил, что его встроенный обратный вызов плюс jQuery css , кажется, работает в большинстве случаев.

Попробуйте эту функцию:

и назовите это так:

Протестировано в IE9, FF4 и Chrome с использованием jQuery 1.5 (для этого НЕ требуется плагин пользовательского интерфейса). Я также не использовал плагин цвета jQuery — он понадобится вам, только если вы хотите использовать именованные цвета (например, ‘yellow’ вместо —- +: = 5 =:. + —-)

У меня была та же проблема, и я смог заставить все работать, когда я включил правильные файлы js.

Я сделал еще один шаг и нашел хорошее расширение, которое кто-то написал.

Приведенный выше код позволяет мне сделать следующее:

Этот код заставит ваш элемент мигать красным, а затем вернется к исходному цвету.

Пользовательский интерфейс jQuery имеет эффект выделения, который делает именно то, что вы хотите.

У вас есть несколько вариантов, например, изменение цвета подсветки.

Анимация backgroundColor не поддерживается в jQuery 1.3.2 (или более ранней версии). Поддерживаются только параметры, которые принимают числовые значения. См. документацию о методе. плагин цветных анимаций добавляет возможность делать это с jQuery 1.2.

Для меня это работало нормально с effects.core.js . Однако я не помню, действительно ли это необходимо. Я думаю, что это работает только с шестнадцатеричными значениями. Вот пример кода наведения, который заставляет вещи исчезать при наведении курсора. Думаю, это может быть полезно:

Мне пришлось использовать файл color.js, чтобы заставить это работать. Я использую jquery 1.4.2.

Просто добавил этот фрагмент ниже сценария jquery, и он сразу начал работать:

Источник

JQuery background color animate not working

I want to change the background color of ‘exampleDiv’ from the original white background to when I call the code below to immediate change the background yellow and then fade back to the original white background.

However, this code does not work.

I have only the JQuery core and JQuery UI linked to my web page.

Why doesn’t the code above work?

9 Answers 9

I’ve had varying success with animate , but found that using its built in callback plus jQuery’s css seems to work for most cases.

Try this function:

and call it like so:

Tested in IE9, FF4, and Chrome, using jQuery 1.5 (do NOT need UI plugin for this). I didn’t use the jQuery color plugin either — you would only need that if you want to use named colors (e.g. ‘yellow’ instead of ‘#FFFF9C’ ).

I had the same problem and I was able to get everything to work when I included the correct js files.

I took it a step further and found a nice extension someone wrote.

The above code allows me to do the following:

That code will get your element to flash to red then back to its original color.

The jQuery UI has a highlight effect that does exactly what you want.

You do have some options like changing the highlight colour.

Animating the backgroundColor is not supported in jQuery 1.3.2 (or earlier). Only parameters that take numeric values are supported. See the documentation on the method. The color animations plugin adds the ability to do this as of jQuery 1.2.

I came across the same issue and ultimately it turned out to be multiple call of jquery’s js file on the page.

While this works absolutely fine with any other methods and also with animate when tried with other css properties like left, but it doesn’t work for background color property in animate method.

Hence, I removed the additional call of jquery’s js file and it worked absolutely fine for me.

For me, it worked fine with effects.core.js . However, I don’t recall whether that’s really required. I think that it only works with hexadecimal values. Here’s a sample hover code that makes things fade as you hover. Thought it might be useful:

I had to use the color.js file to get this to work. I’m using jquery 1.4.2.

Just added this snippet below jquery script and it immediately started working:

Источник

JQuery Анимация не работает над свойством background-color

Я играл с функцией jQuery .animate() и в итоге попытался изменить background-color одного из div в зависимости от количества пикселей, прокручиваемых пользователем. К моему удивлению, это не сработало. Вместо этого я попытался использовать функцию .css() , и она работала хорошо. См. Ссылку jsFiddle внизу.

Может ли кто-нибудь объяснить мне, почему это происходит?

Метод .animate() позволяет нам создавать анимационные эффекты для любого числового свойства CSS.

Свойства и значения анимации

Все анимированные свойства должны быть анимированы до одного числового значения, кроме как указано ниже; большинство свойств, которые не являются числовыми, не могут быть анимированы с использованием базовой функции jQuery (например, width , height или left могут быть анимированы , но background-color не может быть, если только jQuery.Color плагин)

Цвет фона не является числовым свойством, поэтому его нельзя анимировать с помощью .animate() .

Если вы хотите animate свойство background-color , вам нужно либо включить jQueryUI , либо добавить этот плагин:

jQuery UI объединяет плагины jQuery Color, которые обеспечивают цветную анимацию, а также множество функций утилиты для работы с цветами.

Просто добавление к существующим ответам: если вы не хотите использовать JQuery UI для этого, вы можете использовать этот плагин jQuery (только 2.7kB):

Вы можете загрузить jquery.animate-colors.js или jquery.animate-colors.min.js с веб-сайта проекта или включить его из CDN:

После включения вы можете использовать цветные анимации следующим образом:

Вы можете анимировать backgroundColor только с помощью jQueryUI.
Если вы не хотите использовать jQueryUI, вам нужно просто изменить класс и сделать анимацию в CSS с помощью переходов.

Вы также можете анимировать цвет фона с помощью jQuery, только не с помощью метода animate(), как вы заметили, метод css сделает.

Так как это очень просто, не включайте другую библиотеку в код, избавляйтесь от http-запросов и просто делайте это с помощью простого JS.

Источник

jQuery animate backgroundColor

I am trying to animate a change in backgroundColor using jQuery on mouseover.

I have checked some example and I seem to have it right, it works with other properties like fontSize, but with backgroundColor I get and «Invalid Property» js error. The element I am working with is a div.

18 Answers 18

The color plugin is only 4kb so much cheaper than the UI library. Of course you’ll want to use a decent version of the plugin and not some buggy old thing which doesn’t handle Safari and crashes when the transitions are too fast. Since a minified version isn’t supplied you might like test various compressors and make your own min version. YUI gets the best compression in this case needing only 2317 bytes and since it is so small — here it is:

I had the same problem and fixed it by including jQuery UI. Here is the complete script :

Do it with CSS3-Transitions. Support is great (all modern browsers, even IE). With Compass and SASS this is quickly done:

Bitstorm has the best jquery color animation plugin I’ve seen. It’s an improvement to the jquery color project. It also supports rgba.

You can use jQuery UI to add this functionality. You can grab just what you need, so if you want to animate color, all you have to include is the following code. I got if from latest jQuery UI (currently 1.8.14)

It’s only 1.43kb after compressing with YUI:

You can also animate colors using CSS3 transitions but it’s only supported by modern browsers.

Using shorthand property:

Unlike regular javascript transitions, CSS3 transitions are hardware accelerated and therefore smoother. You can use Modernizr, to find out if the browser supports CSS3 transitions, if it didn’t then you can use jQuery as a fallback:

Remember to use stop() to stop the current animation before starting a new one otherwise when you pass over the element too fast, the effect keeps blinking for a while.

For anyone finding this. Your better off using the jQuery UI version because it works on all browsers. The color plugin has issues with Safari and Chrome. It only works sometimes.

You can use 2 divs:

You could put a clone on top of it and fade the original out while fading the clone in.

When the fades are done, restore the original with the new bg.

jsFiddle example

.toggleClass()
.offset()
.fadeIn()
.fadeOut()

I used a combination of CSS transitions with JQuery for the desired effect; obviously browsers which don’t support CSS transitions will not animate but its a lightweight option which works well for most browsers and for my requirements is acceptable degradation.

Jquery to change the background color:

CSS using transition to fade background-color change

These days jQuery color plugin supports following named colors:

I like using delay() to get this done, here’s an example:

This can be called by a function, with «element» being the element class/name/etc. The element will instantly appear with the #FCFCD8 background, hold for a second, then fade into #EFEAEA.

Simply add the following snippet bellow your jquery script and enjoy:

I stumbled across this page with the same issue, but the following problems:

  1. I can’t include an extra jQuery plugin file with my current set-up.
  2. I’m not comfortable pasting large blocks of code that I don’t have time to read over and validate.
  3. I don’t have access to the css.
  4. I hardly had any time for implementation (it was only a visual improvement to an admin page)

With the above that pretty much ruled out every answer. Considering my fade of colour was very simple, I used the following quick hack instead:

The above creates a temporary div that is never placed in the document flow. I then use jQuery’s built-in animation to animate a numeric property of that element — in this case width — which can represent a percentage (0 to 100). Then, using the step function, I transfer this numeric animation to the text colour with a simple hex cacluation.

The same could have been achieved with setInterval , but by using this method you can benefit from jQuery’s animation methods — like .stop() — and you can use easing and duration .

Obivously it’s only of use for simple colour fades, for more complicated colour conversions you’ll need to use one of the above answers — or code your own colour fade math 🙂

Источник

Читайте также:  Не работает помпа стиральной машины канди
Оцените статью