单击时将金额添加到背景位置(jQuery)

发布于 2024-08-18 14:52:51 字数 519 浏览 4 评论 0原文

我对 js 和 jquery 很陌生,所以请耐心等待。

我想更改背景位置,并在单击 #button1 时在 #div1 上添加 1%,并在单击 #button2 时在 #div1 上添加 -1%

我如何在 jQuery 中实现此目的?

另外,奖金问题: 这些将通过 php 动态生成。是否可以在 js 脚本中使用 php 以便 id 正确?

像这样:

$i = 1
while($i <= 5):
 $div[$i] = 'div'.$i;
 $leftbutton[$i] = 'leftbotton'.$i;
 $rightbotton[$i] = 'rightbotton'.$i;
$i++;
endwhile;

否则我也必须学习如何在 js 中创建循环;)

编辑:后续问题:

当我单击按钮时,如何用该值更新文本字段?如果我还想添加向上/向下按钮,我该如何修改它?非常感谢!

提前致谢! -西蒙

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'.$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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘虞初梦 2024-08-25 14:52:51

像这样:

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);

编辑:修正错误。

演示

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文