开发者

Adding amount to background-position on click (jQuery)

I pretty new to js and jquery so please bear with me.

I'd like to change the background-position and add 1% on #div1 while clicking on #button1 and take -1% on #div1 while clicking on #button2

How could i achive this in jQuery?

Alse, bonus question: These are going to get dynamically generated through php. Is it possible to use php in the js-script so the id's get correct?

like this:

$i = 1
while($i <= 5):
 $div[$i] = 'div'.$i;
 $leftbutton[$i] = 'leftbotton'.$i;
 $rightbotton[$i] = 'rightbotton'开发者_如何学Go.$i;
$i++;
endwhile;

Else i'll have to learn how to make loops in js as well ;)

Edit: Follow up questions:

How can i update a text field with this value as i click the buttons? And how do i modify it if i'd like to add up/down buttons as well? thanks a bunch!

Thanks in advance! -Simon


Like this:

function makeClicker(index) {
    $('#leftbutton' + index).click(function() {
        var bPos = $('#div' + index).css('background-position');
        bPos = bPos.replace(/%/g, '').split(' ');
        bPos = (-1 + parseInt(bPos[0], 0)) + '% ' + bPos[1] + '%';
        $('#div' + index).css('background-position', bPos);
    });
    $('#rightbutton' + index).click(function() {
        var bPos = $('#div' + index).css('background-position');
        bPos = bPos.replace(/%/g, '').split(' ');
        bPos = (1 + parseInt(bPos[0], 0)) + '% ' + bPos[1] + '%';
        $('#div' + index).css('background-position', bPos);
    });
}

for(var i = 1; i <= 5; i++)
    makeClicker(i);

EDIT: Fixed mistakes.

Demo

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜