繁体   English   中英

用Javascript移动图片

[英]Moving pictures with Javascript

我的网站有问题,或者至少我认为有问题。 我使用一个非常简单的几乎递归的Javascript函数来移动两张图片。 但是,在我四岁的计算机上,这并不是一个平稳的动作。 我缩小了图片的尺寸,但是...

该代码不是递归的,因为我在两次调用之间使用setTimeout。

代码如下:(onload)

sImgArray = ["imgLaVera", "imgAlmanzor", "imgRosarito", "imgBaile"];
iImg = sImgArray.length - 1;
setTimeout('playShow(0,' + iImg + ')', 4000);

function playShow(iVisible, iImgs)
{
    if( iVisible < iImgs )
        iLeft = iVisible + 1;
    else
        iLeft = 0;

    imgLeft = document.getElementById(sImgArray[iLeft]);
    imgLeft.style.left = "-" + imgLeft.width + "px";
    playMove(-imgLeft.width, iVisible, iImgs);
}
function playMove(i, iVisible, iImgs)
{
    if( iVisible < iImgs )
        iLeft = iVisible + 1;
    else
        iLeft = 0;

    imgLeft = document.getElementById(sImgArray[iLeft]);
    imgRight = document.getElementById(sImgArray[iVisible]);

    if( i < 0 )
    {
        i = i + 5;
        imgLeft.style.left = (i - 2) + "px";
        imgRight.style.left = (i + imgLeft.width) + "px";
        setTimeout('playMove(' + i + ', ' + iVisible + ',' + iImgs + ')', 75);
    }
    else
    {
        if( iVisible < iImgs )
            iVisible = iVisible + 1;
        else
            iVisible = 0;
        setTimeout('playShow(' + iVisible + ',' + iImgs + ')', 4000)
    }
}

有什么建议么?

好像您每75毫秒前进一次动画。 那是ca。 每秒13个步骤。 每秒至少需要24步才能平稳移动。 我建议33毫秒(每秒30步)或16毫秒(每秒60步)。 jQuery用于动画的时间是16毫秒(jQuery非常擅长此操作)。

playMove的以下设置将为您提供所需的内容:

i = i + 1;
setTimeout('playMove( ... )', 15);

您的动画似乎呆滞,因为您很少更改图像位置并且跳得很大 如果希望它更平滑 ,则应更频繁地更改位置,但每一步中的像素要少一些。

Old: 5 px / 75 ms
New: 1 px / 15 ms

图片的标题说明

如果您确实关心速度,请不要在每次调用渲染函数( playMove )时都选择元素。 show结束时,在调用setTimeout之前执行此操作:

// select elements by their id and replace them in the array
for (var i = sImgArray.length; i--;) {
  sImgArray[i] = document.getElementById( sImgArray[i] );
}

现在您可以简单地写

sImgArray[iLeft]

代替

document.getElementById(sImgArray[iLeft])

在playMove和playShow中。

其次,您应避免将函数作为文本参数传递,因为它们需要分别规避。

// GOOD
setTimeout(function() {
    playShow(iVisible, iImgs);
}, 4000);

// BAD
setTimeout('playShow(' + iVisible + ',' + iImgs + ')', 4000)

第三,这就像我一生中看到的最丑陋的东西:

setTimeout('show.call(\'index\');', 6000);

不要使用this引用将参数传递给函数。 这就是普通参数列表的用途。

setTimeout(function() {
    show('index');
}, 4000);

然后,您的功能show将变成这样:

function show( page ) // pass string as an argument
{
    if ( page == "index" )
    {
    // ...

我建议您使用一个库来帮助您实现这一目标。 例如jQuery ,其中有一些示例: http : //api.jquery.com/animate/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM