•
Animare pozitie background
•
Obtinere pozitie background
Acest tutorial arata cum se poate
schimba, anima si obtine pozitia unei imagini de fundal (background) din elementele HTML, cu
jQuery.
Daca doriti pur si simplu sa setati sau sa modificati pozitia imaginii de fundal, folositi aceasta sintaxa:
$(selector).css({ backgroundPosition: 'Xval Yval' })
-
Xval - reprezinta valoarea pentru pozitia orizontala.
-
Yval - reprezinta valoarea pentru pozitia verticala.
Exemple schimbare pozitie background
1. Cand se apasa pe un buton, plaseaza imaginea de fundal in dreapta-jos.
<style type="text/css">
#idex1 {
width:320px;
height:80px;
background:url('image.jpg') 0 0 no-repeat;
border:1px solid blue;
}
</style>
<div id="idex1"></div>
<button id="bex1">Clic</button>
<script type="text/javascript"><!--
$('#bex1').click(function(){
$('#idex1').css({backgroundPosition: '100% 100%'});
});
--></script>
Demo:
2. Cand cursorul mouse-ului e deasupra unui anumit element, centreaza pe orizontala imaginea de fundal, iar pe verticala 25 pixeli fata de marginea de sus (top).
<style type="text/css">
#idex2 {
width:320px;
height:80px;
background:url('image.jpg') 0 0 no-repeat;
border:1px solid blue;
}
</style>
<div id="idex2"></div>
<script type="text/javascript"><!--
$('#idex2').mouseover(function(){
$(this).css({backgroundPosition: '50% 25px'});
});
$('#idex2').mouseout(function(){
$(this).css({backgroundPosition: '0 0'});
});
--></script>
Demo (plasati cursorul mouse-ului deasupra cadrului):
3. Cand se apasa pe un buton, shimba pozitia imaginii de fundal stanga, dreapta.
<style type="text/css"><!--
#idex3 {
background: url('image.jpg') 0 center no-repeat;
width:400px;
height:80px;
border:1px dashed green;
}
--></style>
<div id="idex3"></div>
<button id="bex3">Clic</button>
<script type="text/javascript"><!--
// http://www.coursesweb.net
var ix = 1;
$('#bex3').click(function() {
$('#idex3').css({ 'background-position': (100 * (ix % 2)) +'% 50%' });
ix++;
});
--></script>
Demo (clic pe buton de cateva ori):
Animare pozitie background
Cea mai usoara metoda de a schimba pozitia imaginii de fundal cu o miscare animata, cu jQuery, este folosind urmatorul plugin (scris de Keith Wood -
http://keith-wood.name/backgroundPos.html).
1. Copiati urmatorul cod intr-un fisier ".js" (de exemplu, cu numele "jquery_backgroundpos.js").
Plugin jQuery animare pozitie background
(function($){var BG_POS='bgPos';$.fx.step['backgroundPosition']=$.fx.step['background-position']=function(fx){if(!fx.set){var elem=$(fx.elem);var bgPos=elem.data(BG_POS);elem.css('backgroundPosition',bgPos);fx.start=parseBackgroundPosition(bgPos);fx.end=parseBackgroundPosition($.fn.jquery>='1.6'?fx.end:fx.options.curAnim['backgroundPosition']||fx.options.curAnim['background-position']);for(var i=0;i<fx.end.length;i++){if(fx.end[i][0]){fx.end[i][1]=fx.start[i][1]+(fx.end[i][0]=='-='?-1:+1)*fx.end[i][1];}}
fx.set=true;}
$(fx.elem).css('background-position',((fx.pos*(fx.end[0][1]-fx.start[0][1])+fx.start[0][1])+fx.end[0][2])+' '+
((fx.pos*(fx.end[1][1]-fx.start[1][1])+fx.start[1][1])+fx.end[1][2]));};function parseBackgroundPosition(value){var presets={center:'50%',left:'0%',right:'100%',top:'0%',bottom:'100%'};var bgPos=value.split(/ /);var decodePos=function(index){var pos=(presets[bgPos[index]]||bgPos[index]||'50%').match(/^([+-]=)?([+-]?\d+(\.\d*)?)(.*)$/);bgPos[index]=[pos[1],parseFloat(pos[2]),pos[4]||'px'];};if(bgPos.length==1&&$.inArray(bgPos[0],['top','bottom'])>-1){bgPos[1]=bgPos[0];bgPos[0]='50%';}
decodePos(0);decodePos(1);return bgPos;}
$.fn.animate=function(origAnimate){return function(prop,speed,easing,callback){if(prop['backgroundPosition']||prop['background-position']){this.data(BG_POS,this.css('backgroundPosition')||'center');}
return origAnimate.apply(this,[prop,speed,easing,callback]);};}($.fn.animate);})(jQuery);
2. Includeti plugin-ul in document HTML, dupa libraria de functii jQuery.
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery_backgroundpos.js"></script>
3. Aplicati metoda
animate(), cu aceasta sintaxa:
$(selector).animate({ backgroundPosition: 'Xval Yval' }, speed);
- Xval si Yval reprezinta valorile pe orizontala si verticala pt background. Acestea pot fi valori absolute (ex.
-100px sau 50px), procente (ex.
-25% sau 50%), valori relative (ex.
-=200px sau +=20%), ori cu nume definit (
top, left, right, bottom).
Daca valoarea pt verticala e omisa, se considera '50%'.
Daca nu e specificata unitatea de masura, se foloseste 'px'.
- "speed" - e optional, determina viteza animatiei ("fast", "slow", sau milisecunde).
Exemplu de cod:
$(selector).animate({backgroundPosition: '-120px 0'}, 1500);
$(selector).animate({backgroundPosition: '30% -15%'}, 'fast');
$(selector).animate({backgroundPosition: '+=100px -=80px'}, 'slow', 'linear');
$(selector).animate({backgroundPosition: 'left bottom'});
Exemple Animare pozitie background
1. Cand se apasa pe un buton, muta animat imaginea de fundal din stanga-sus in dreapta-jos.
<style type="text/css">
#idex4 {
width:320px;
height:80px;
background:url('image.jpg') 0 0 no-repeat;
border:1px solid blue;
}
</style>
<div id="idex4"></div>
<button id="bex4">Clic</button>
<script type="text/javascript"><!--
$('#bex4').click(function(){
$('#idex4').animate({backgroundPosition: '100% 100%'}, 1500);
});
--></script>
Demo:
2. Muta imaginea de fundal alternativ stanga, dreapta, cu miscare animata. Afiseaza si numarul de clic-uri:
<style type="text/css"><!--
#idex5 {
background: url('image.jpg') 0 center no-repeat;
width:400px;
height:80px;
border:1px dashed green;
}
--></style>
<div id="idex5"></div>
<button id="bex5">Clic</button>
<script type="text/javascript"><!--
// http://www.coursesweb.net
var vx = 1;
var nrclicks = 0; // retine numarul de clic-uri
$('#bex5').click(function() {
$('#idex5').animate({
backgroundPosition: (100 * (vx % 2)) +'% 50%' }, 'slow', 'linear',
// functie in animate() ca sa incrementeze si sa afiseze numarul de clic-uri
function(){
nrclicks++;
$('#idex5').html('<h4>'+ nrclicks+ '</h4>')
}
);
vx++;
});
--></script>
Demo (clic pe buton de cateva ori):
Obtinere pozitie background
Ca sa obtineti pozitia imaginii de background, folositi aceasta functie.
// Returneaza un obiect cu valori pt pozitia background - http://snipplr.com/view/50791/
function getBackgroundPos(obj) {
var pos = obj.css('background-position');
if (pos == 'undefined' || pos == null) {
// pt IE
pos = [obj.css('background-position-x'),obj.css('background-position-y')];
}
else {
pos = pos.split(' ');
}
return {
x: parseFloat(pos[0]),
xUnit: pos[0].replace(/[0-9-.]/g, ''),
y: parseFloat(pos[1]),
yUnit: pos[1].replace(/[0-9-.]/g, '')
};
}
Aceasta functie returneaza un obiect cu patru proprietati:
-
x - valoarea numerica pt pozitia orizontala (in IE este transformata in pixeli).
-
xUnit - unitatea de masura pt valoarea "x" (in IE este 'px').
-
y - valoarea numerica pt pozitia verticala (in IE este transformata in pixeli).
-
yUnit - unitatea de masura pt valoarea "y" (in IE este 'px').
• Utilizare functie getBackgroundPos():
var bgpos = getBackgroundPos($('#id'));
// bgpos.x
// bgpos.xUnit
// bgpos.y
// bgpos.yUnit
Exemplu:
<style type="text/css">
#idex6 {
width:320px;
height:80px;
background:url('image.jpg') 50% 15% no-repeat;
border:2px dotted green;
}
</style>
<div id="idex6"></div>
<button id="bex6">Get backgroundPosition</button>
<script type="text/javascript"><!--
// functie pt obtinere pozitie background
function getBackgroundPos(obj) {
var pos = obj.css('background-position');
if (pos == 'undefined' || pos == null) {
// for IE
pos = [obj.css('background-position-x'),obj.css('background-position-y')];
}
else {
pos = pos.split(' ');
}
return {
x: parseFloat(pos[0]),
xUnit: pos[0].replace(/[0-9-.]/g, ''),
y: parseFloat(pos[1]),
yUnit: pos[1].replace(/[0-9-.]/g, '')
};
}
// la clic pe #bex6
$('#bex6').click(function(){
// obtine obiectul cu vaalori x/y background-position
var bgpos = getBackgroundPos($('#idex6'));
var Xval = bgpos.x + bgpos.xUnit; // pozitia orizontala
var Yval = bgpos.y + bgpos.yUnit; // pozitia verticala
alert('backgroundPosition: "'+ Xval+ ' '+ Yval+ '"');
});
--></script>
Demo: