最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - slide an image left or right - Stack Overflow

programmeradmin3浏览0评论

How do 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?

How do 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?

Share Improve this question asked Feb 8, 2011 at 22:31 Bogdan VerbenetsBogdan Verbenets 27k13 gold badges72 silver badges120 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

jQuery has a built-in method called animate.

An example of using it:

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

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

jQuery sure does :)

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

Code example (slightly modified from the jQuery) is below and I've made a working jsFiddle: http://jsfiddle/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/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)

  1. 暂无评论