开发者

slide an image left or right

How d开发者_C百科o you slide an image left/right using javascript? I want an image to slowly slide to the right. Do you use javascript's setTimeout function to gradually change element style's "left" value? Maybe jQuery has a function for that?


jQuery has a built-in method called animate.

An example of using it:

$('#id').animate({
    left: 200
});

More: http://api.jquery.com/animate/


jQuery sure does :)

There's a built in .animate() function: http://api.jquery.com/animate/

Code example (slightly modified from the jQuery) is below and I've made a working jsFiddle: http://jsfiddle.net/Damien_at_SF/HRBkN/

CSS:

img.block {
  position:absolute;
  left:50px;
  top:50px;
  margin:5px;
}

HTML:

<button id="left">left</button> <button id="right">right</button>
<img src="http://jsfiddle.net/img/logo.png" class="block" />

JS for absolute positioned img:

$("#right").click(function(){
  $(".block").animate({"left": "+=50px"}, "slow");
});

$("#left").click(function(){
  $(".block").animate({"left": "-=50px"}, "slow");
});

JS for relative/static positioned img:

$("#right").click(function(){
  $(".block").animate({"margin-left": "+=50px"}, "slow");
});

$("#left").click(function(){
  $(".block").animate({"margin-left": "-=50px"}, "slow");
});

Hope that helps:)


For what its worth, I have this fiddle that does it without .animate(). I haven't used .animate() but I'm gonna check it out after reading this post.


I can sliding the image to left and right side with the following:

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName("mySlides");

    if (n > x.length) 
    {
        slideIndex = 1
    }

    if (n < 1) 
    {
        slideIndex = x.length
    }

    for (i = 0; i < x.length; i++) 
    {
        x[i].style.display = "none";  
    }

    x[slideIndex-1].style.display = "block";  
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜