开发者

Images, setInterval and Mouseover

开发者 https://www.devze.com 2023-04-12 03:10 出处:网络
I have a problem with a script that cycles through images. Once the mouse pointer moves over an image, i want to pause the script (InfinityLoop). As the mouse leaves the image, the script should cont

I have a problem with a script that cycles through images.

Once the mouse pointer moves over an image, i want to pause the script (InfinityLoop). As the mouse leaves the image, the script should continue.

Here is the example running: http://jsfiddle.net/64W8u/

I'am trying since days, but didn't get it running :-/

Thanks for y开发者_运维知识库our great help here!

var j = jQuery.noConflict();

jQuery(document).ready(function()
{
/* stage functions */
j("#small img").mouseover(function()
{
    stageReset();
    var imageurl = j(this).attr("src");
    var aimage = imageurl.replace(".jpg", "_a.jpg");
    var bimage = imageurl.replace(".jpg", "_b.jpg");
    j(this).attr("src", aimage);
    j("#big img").attr("src", bimage);
});

j("#small img").mouseout(function()
{
    var imageurl = j(this).attr("src");
    var aimage = imageurl.replace("_a.jpg", ".jpg");
    j(this).attr("src",aimage);
});

function stageReset()
{
    j("#small img").each(function()
    {
        var reseturl = j(this).attr("src");
        reseturl = reseturl.replace("_a.jpg", ".jpg");
        j(this).attr("src", reseturl);
    });
}
}

jQuery.fn.stageCycle = function()
{
var itemInterval = 2000;
var numberOfItems = j("#small img").length;
var currentItem = 0;

var InfinityLoop = setInterval(function()
    {
    var url = j("#small img").eq(currentItem).attr("src");
    var urla = url.replace(".jpg","_a.jpg");
    var urlb = url.replace(".jpg","_b.jpg");

    stageReset();

    j("#small img").eq(currentItem).attr("src",urla);
    j("#big img").attr("src",urlb);


    if(currentItem == numberOfItems-1)
        {
        currentItem = 0;
        }
    else
        {
        currentItem++;
        }

    }, itemInterval);
};

j(window).stageCycle();

});


I would not be using setInterval() for this. Instead, use setTimeout() with a function that, after swapping to the next image to be shown, will start another setTimeout(). You can then achieve your desired mouseover functionality by calling clearTimeout() on the id returned by the setTimeout() calls, and on mouseout you call setTimeout() again to restart the loop.

Example:

var img = document.getElementById("imd_id");
var nextImageTimer;
function showNextImage() {
    img.src = "NEXT_IMAGE_URL";
    nextImageTimer = setTimeout(showNextImage, 1000);
}

// In your mouseover:
clearTimeout(nextImageTimer);

// And in your mouseout:
nextImageTimer = setTimeout(showNextImage, 1000);
0

精彩评论

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

关注公众号