jQuery 两个按钮使图片从左向右移动

jQuery Two buttons making a picture move from left to right

本文关键字:移动 右移 按钮 两个 jQuery      更新时间:2023-09-26
我想

让图片(火柴人图片)从左向右移动,因为我单击显示"<<"和">>"的两个按钮之一。这是我的代码,

function personLeft() {
                $('#img').animate({left:'50px'});
            }
function personRight() {
                $('#img').animate({right:'50px'});
            }

这是按钮,

<button id='left' onclick='personRight()'><<</button>
<button id='right' onclick='personLeft()'>>></button>

出于某种原因,这不起作用。它只使他向右旅行一次,或向左旅行一次。我试过这样做:

$(document).ready(function(){
    $('#left').click(function(){
        $('#img').animate({left:'50px'});
    });
    $('#right').click(function(){
        $('#img').animate({left:'50px'});
    });
});

但它只是做了与函数相同的事情。如果您需要了解我的意思,这里是链接。

所以,我想知道的是,如何做到每次我点击右键时,它都会向右移动 50 像素,每次单击左按钮时,它会向左移动 50 像素。

您目前只是将其位置设置为 50px,您要做的是从其当前位置添加 50px:

$('#left').click(function(){
    $('#img').animate({
        left:'+=50px'
    });
});

检查 http://www.w3schools.com/jquery/jquery_animate.asp - 使用相对值以获取更多信息

您可以尝试将元素向左移动。

$('#left').click(function(){
    $('#img').animate({left:'-50px'});
});

对于向左移动,请尝试此操作

$('#img').animate({left:'-50px'});

不是直接指定50px而是需要从前一个值中添加或减去它。

尝试做类似的事情

$('#left').click(function(){
    var left = parseInt($('#img').css('left'));
    $('#img').animate({left:(left - 50) + 'px'});
});

对于#right来说类似的东西