jQueryアニメーションbackgroundColor
-
07-07-2019 - |
質問
マウスオーバーでjQueryを使用してbackgroundColorの変化をアニメーション化しようとしています。
いくつかの例をチェックしましたが、正しいようです。fontSizeなどの他のプロパティで動作しますが、backgroundColorでは「無効なプロパティ」を取得します。 jsエラー。 作業している要素はdivです。
$(".usercontent").mouseover(function() {
$(this).animate({ backgroundColor: "olive" }, "slow");
});
アイデアはありますか
解決
カラープラグインは4 KBしかないため、UIライブラリよりもはるかに安価です。もちろん、適切なバージョンのプラグインを使用する必要があります。 http://plugins.jquery.com/project/color "rel =" noreferrer ">バグのある古いもの。Safariを処理せず、遷移が速すぎるとクラッシュします。縮小版は提供されていないため、さまざまなコンプレッサーをテストし、独自の最小バージョンをテストすることができます。この場合、YUIは2317バイトしか必要とせず、非常に小さいため、最高の圧縮を取得します-ここにあります:
(function (d) {
d.each(["backgroundColor", "borderBottomColor", "borderLeftColor", "borderRightColor", "borderTopColor", "color", "outlineColor"], function (f, e) {
d.fx.step[e] = function (g) {
if (!g.colorInit) {
g.start = c(g.elem, e);
g.end = b(g.end);
g.colorInit = true
}
g.elem.style[e] = "rgb(" + [Math.max(Math.min(parseInt((g.pos * (g.end[0] - g.start[0])) + g.start[0]), 255), 0), Math.max(Math.min(parseInt((g.pos * (g.end[1] - g.start[1])) + g.start[1]), 255), 0), Math.max(Math.min(parseInt((g.pos * (g.end[2] - g.start[2])) + g.start[2]), 255), 0)].join(",") + ")"
}
});
function b(f) {
var e;
if (f && f.constructor == Array && f.length == 3) {
return f
}
if (e = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)) {
return [parseInt(e[1]), parseInt(e[2]), parseInt(e[3])]
}
if (e = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)) {
return [parseFloat(e[1]) * 2.55, parseFloat(e[2]) * 2.55, parseFloat(e[3]) * 2.55]
}
if (e = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)) {
return [parseInt(e[1], 16), parseInt(e[2], 16), parseInt(e[3], 16)]
}
if (e = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)) {
return [parseInt(e[1] + e[1], 16), parseInt(e[2] + e[2], 16), parseInt(e[3] + e[3], 16)]
}
if (e = /rgba\(0, 0, 0, 0\)/.exec(f)) {
return a.transparent
}
return a[d.trim(f).toLowerCase()]
}
function c(g, e) {
var f;
do {
f = d.css(g, e);
if (f != "" && f != "transparent" || d.nodeName(g, "body")) {
break
}
e = "backgroundColor"
} while (g = g.parentNode);
return b(f)
}
var a = {
aqua: [0, 255, 255],
azure: [240, 255, 255],
beige: [245, 245, 220],
black: [0, 0, 0],
blue: [0, 0, 255],
brown: [165, 42, 42],
cyan: [0, 255, 255],
darkblue: [0, 0, 139],
darkcyan: [0, 139, 139],
darkgrey: [169, 169, 169],
darkgreen: [0, 100, 0],
darkkhaki: [189, 183, 107],
darkmagenta: [139, 0, 139],
darkolivegreen: [85, 107, 47],
darkorange: [255, 140, 0],
darkorchid: [153, 50, 204],
darkred: [139, 0, 0],
darksalmon: [233, 150, 122],
darkviolet: [148, 0, 211],
fuchsia: [255, 0, 255],
gold: [255, 215, 0],
green: [0, 128, 0],
indigo: [75, 0, 130],
khaki: [240, 230, 140],
lightblue: [173, 216, 230],
lightcyan: [224, 255, 255],
lightgreen: [144, 238, 144],
lightgrey: [211, 211, 211],
lightpink: [255, 182, 193],
lightyellow: [255, 255, 224],
lime: [0, 255, 0],
magenta: [255, 0, 255],
maroon: [128, 0, 0],
navy: [0, 0, 128],
olive: [128, 128, 0],
orange: [255, 165, 0],
pink: [255, 192, 203],
purple: [128, 0, 128],
violet: [128, 0, 128],
red: [255, 0, 0],
silver: [192, 192, 192],
white: [255, 255, 255],
yellow: [255, 255, 0],
transparent: [255, 255, 255]
}
})(jQuery);
他のヒント
同じ問題があり、jQuery UIを含めることで修正しました。完全なスクリプトは次のとおりです。
<!-- include Google's AJAX API loader -->
<script src="http://www.google.com/jsapi"></script>
<!-- load JQuery and UI from Google (need to use UI to animate colors) -->
<script type="text/javascript">
google.load("jqueryui", "1.5.2");
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#menu ul li.item').hover(
function() {
$(this).stop().animate({backgroundColor:'#4E1402'}, 300);
}, function () {
$(this).stop().animate({backgroundColor:'#943D20'}, 100);
});
});
</script>
CSS3-Transitionsで実行します。サポートは素晴らしいです(すべての最新のブラウザー、IEも)。 CompassとSASSを使用すると、これはすぐに完了します。
#foo {background:red; @include transition(background 1s)}
#foo:hover {background:yellow}
純粋なCSS:
#foo {
background:red;
-webkit-transition:background 1s;
-moz-transition:background 1s;
-o-transition:background 1s;
transition:background 1s
}
#foo:hover {background:yellow}
このトピックに関するドイツ語の記事 http://www.solifeを書きました。 cc / blog / animation-farben-css3-transition.html
Bitstormには、私が見た中で最高のjqueryカラーアニメーションプラグインがあります。 jquery colorプロジェクトの改善です。 rgbaもサポートしています。
jQuery UIを使用して、この機能を追加できます。必要なものだけをつかむことができるので、色をアニメーション化する場合、含める必要があるのは次のコードだけです。最新のjQuery UI(現在は1.8.14)から取得できます
/******************************************************************************/
/****************************** COLOR ANIMATIONS ******************************/
/******************************************************************************/
// override the animation for color styles
$.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor',
'borderRightColor', 'borderTopColor', 'borderColor', 'color', 'outlineColor'],
function(i, attr) {
$.fx.step[attr] = function(fx) {
if (!fx.colorInit) {
fx.start = getColor(fx.elem, attr);
fx.end = getRGB(fx.end);
fx.colorInit = true;
}
fx.elem.style[attr] = 'rgb(' +
Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0], 10), 255), 0) + ',' +
Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1], 10), 255), 0) + ',' +
Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2], 10), 255), 0) + ')';
};
});
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if ( color && color.constructor == Array && color.length == 3 )
return color;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return [parseInt(result[1],10), parseInt(result[2],10), parseInt(result[3],10)];
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
return colors['transparent'];
// Otherwise, we're most likely dealing with a named color
return colors[$.trim(color).toLowerCase()];
}
function getColor(elem, attr) {
var color;
do {
color = $.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") )
break;
attr = "backgroundColor";
} while ( elem = elem.parentNode );
return getRGB(color);
};
YUIで圧縮すると、わずか1.43kbです:
$.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","borderColor","color","outlineColor"],function(b,a){$.fx.step[a]=function(c){if(!c.colorInit){c.start=getColor(c.elem,a);c.end=getRGB(c.end);c.colorInit=true}c.elem.style[a]="rgb("+Math.max(Math.min(parseInt((c.pos*(c.end[0]-c.start[0]))+c.start[0],10),255),0)+","+Math.max(Math.min(parseInt((c.pos*(c.end[1]-c.start[1]))+c.start[1],10),255),0)+","+Math.max(Math.min(parseInt((c.pos*(c.end[2]-c.start[2]))+c.start[2],10),255),0)+")"}});function getRGB(b){var a;if(b&&b.constructor==Array&&b.length==3){return b}if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(b)){return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)]}if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(b)){return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55]}if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(b)){return[parseInt(a[1],16),parseInt(a[2],16),parseInt(a[3],16)]}if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(b)){return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)]}if(a=/rgba\(0, 0, 0, 0\)/.exec(b)){return colors.transparent}return colors[$.trim(b).toLowerCase()]}function getColor(c,a){var b;do{b=$.curCSS(c,a);if(b!=""&&b!="transparent"||$.nodeName(c,"body")){break}a="backgroundColor"}while(c=c.parentNode);return getRGB(b)};
CSS3トランジションを使用して色をアニメーション化することもできますが、最新のブラウザでのみサポートされています。
a.test {
color: red;
-moz-transition-property: color; /* FF4+ */
-moz-transition-duration: 1s;
-webkit-transition-property: color; /* Saf3.2+, Chrome */
-webkit-transition-duration: 1s;
-o-transition-property: color; /* Opera 10.5+ */
-o-transition-duration: 1s;
-ms-transition-property: color; /* IE10? */
-ms-transition-duration: 1s;
transition-property: color; /* Standard */
transition-duration: 1s;
}
a.test:hover {
color: blue;
}
ショートハンドプロパティの使用:
/* shorthand notation for transition properties */
/* transition: [transition-property] [transition-duration] [transition-timing-function] [transition-delay]; */
a.test {
color: red;
-moz-transition: color 1s;
-webkit-transition: color 1s;
-o-transition: color 1s;
-ms-transition: color 1s;
transition: color 1s;
}
a.test {
color: blue;
}
通常のjavascript遷移とは異なり、CSS3遷移はハードウェアで加速されるため、よりスムーズになります。 Modernizrを使用して、ブラウザーがCSS3トランジションをサポートしているかどうかを確認できます。サポートされていない場合は、フォールバックとしてjQueryを使用できます。
if ( !cssTransitions() ) {
$(document).ready(function(){
$(".test").hover(function () {
$(this).stop().animate({ backgroundColor: "red" },500)
}, function() {
$(this).stop().animate({ backgroundColor: "blue" },500)}
);
});
}
stop()を使用して、新しいアニメーションを開始する前に現在のアニメーションを停止することを忘れないでください。
これを見つけた人のために。 jQuery UIバージョンはすべてのブラウザーで機能するため、jQuery UIバージョンを使用することをお勧めします。カラープラグインには、SafariとChromeに問題があります。時々しか動作しません。
2つのdivを使用できます:
その上にクローンを置き、クローンをフェードインしながらオリジナルをフェードアウトすることができます。
フェードが完了したら、新しいbgで元の状態に戻します。
$(function(){
var $mytd = $('#mytd'), $elie = $mytd.clone(), os = $mytd.offset();
// Create clone w other bg and position it on original
$elie.toggleClass("class1, class2").appendTo("body")
.offset({top: os.top, left: os.left}).hide();
$mytd.mouseover(function() {
// Fade original
$mytd.fadeOut(3000, function() {
$mytd.toggleClass("class1, class2").show();
$elie.toggleClass("class1, class2").hide();
});
// Show clone at same time
$elie.fadeIn(3000);
});
});
jsFiddleの例
目的の効果を得るために、CSSトランジションとJQueryの組み合わせを使用しました。明らかに、CSSトランジションをサポートしないブラウザーはアニメーション化されませんが、ほとんどのブラウザーと私の要件に適した軽量オプションは許容可能な劣化です。
Jqueryで背景色を変更します:
$('.mylinkholder a').hover(
function () {
$(this).css({ backgroundColor: '#f0f0f0' });
},
function () {
$(this).css({ backgroundColor: '#fff' });
}
);
遷移を使用して背景色のフェードを変更するCSS
.mylinkholder a
{
transition: background-color .5s ease-in-out;
-moz-transition: background-color .5s ease-in-out;
-webkit-transition: background-color .5s ease-in-out;
-o-transition: background-color .5s ease-in-out;
}
最近のjQueryカラープラグインは、次の名前付きカラーをサポートしています。
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]
これを実現するためにdelay()を使用するのが好きです。以下に例を示します:
jQuery(element).animate({ backgroundColor: "#FCFCD8" },1).delay(1000).animate({ backgroundColor: "#EFEAEA" }, 1500);
これは、&quot; element&quot;を使用して関数から呼び出すことができます。要素のクラス/名前/など。要素はすぐに#FCFCD8バックグラウンドで表示され、1秒間押した後、#EFEAEAにフェードインします。
次のスニペットをjqueryスクリプトの下に追加してお楽しみください:
<script src="https://cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>
同じ問題でこのページを見つけましたが、次の問題があります:
- 現在のセットアップに追加のjQueryプラグインファイルを含めることはできません。
- 読み直して検証する時間がない大きなコードブロックを貼り付けるのは苦手です。
- CSSにアクセスできません。
- 実装する時間がほとんどありませんでした(管理ページの視覚的な改善に過ぎませんでした)
上記では、すべての回答がほとんど除外されました。私の色あせは非常に簡単だと考えて、代わりに次のクイックハックを使用しました。
element
.css('color','#FF0000')
;
$('<div />')
.css('width',0)
.animate(
{'width':100},
{
duration: 3000,
step:function(now){
var v = (255 - 255/100 * now).toString(16);
v = (v.length < 2 ? '0' : '') + v.substr(0,2);
element.css('color','#'+v+'0000');
}
}
)
;
上記は、ドキュメントフローに配置されない一時的なdivを作成します。次に、jQueryの組み込みアニメーションを使用して、その要素の数値プロパティ(この場合は width
)をアニメーション化し、パーセンテージ(0〜100)を表すことができます。次に、step関数を使用して、この数値アニメーションを単純な16進法でテキストの色に変換します。
setInterval
でも同じことが実現できますが、このメソッドを使用すると、jQueryのアニメーションメソッド( .stop()
など)を活用でき、< code> easing および duration
。
明らかに、単純な色の退色にのみ使用され、より複雑な色の変換には、上記の回答のいずれかを使用するか、独自の色の退色の数学をコーディングする必要があります:)
これを試してください:
(function($) {
var i = 0;
var someBackground = $(".someBackground");
var someColors = [ "yellow", "red", "blue", "pink" ];
someBackground.css('backgroundColor', someColors[0]);
window.setInterval(function() {
i = i == someColors.length ? 0 : i;
someBackground.animate({backgroundColor: someColors[i]}, 3000);
i++;
}, 30);
})(jQuery);
例をプレビューできます: http://jquerydemo.com/demo/ jquery-animate-background-color.aspx
ColorBlendプラグインは、まさにあなたが望むことをします
http://plugins.jquery.com/project/colorBlend
これが私のハイライトコードです
$("#container").colorBlend([{
colorList:["white", "yellow"],
param:"background-color",
cycles: 1,
duration: 500
}]);
jQueryのコア機能のみを使用して背景をアニメーション化したくない場合は、これを試してください:
jQuery(".usercontent").mouseover(function() {
jQuery(".usercontent").animate({backgroundColor:'red'}, 'fast', 'linear', function() {
jQuery(this).animate({
backgroundColor: 'white'
}, 'normal', 'linear', function() {
jQuery(this).css({'background':'none', backgroundColor : ''});
});
});
使用してみてください
-moz-transition: background .2s linear;
-webkit-transition: background .2s linear;
-o-transition: background .2s linear;
transition: background .2s linear;
これを試してください:
jQuery(".usercontent").hover(function() {
jQuery(this).animate({backgroundColor:"pink"}, "slow");
},function(){
jQuery(this).animate({backgroundColor:"white"}, "slow");
});
エフェクトの修正方法:
jQuery(".usercontent").hover(function() {
jQuery(this).fadeout("slow",function(){
jQuery(this).animate({"color","yellow"}, "slow");
});
});