使用jquery将图像水平移动到左侧

时间:2011-05-08 10:40:32

标签: javascript jquery

我有一个简单的html页面,在div工具栏中有3个图像。图像放置在工具栏的右端。单击任何图像时,我想将其移动到左端。将2张图片放在最右边。

这是我的HTML

<div id="toolbar" align="right">
    <img id="home" src="home.png" alt="image"/>
    <img id="learn" src="learn.png" alt="image"/>
    <img id="gallery" src="gallery.png" alt="image"/>       
</div>

这是我的css

#toolbar{
    position: relative;
    margin: 0 auto;
    width: 1257px;
    height: 60px;
    border:1px solid #000000;
}

以下是我在提到彼得和阿卜杜拉的答案后得到的结论

 $('#toolbar img').click(function(e){
  if(e.target.id=="home")
      {
        $("#home").css({'float':'left','margin':'0px'});
        $("#learn").css({'float':'right','margin':'0px'});
        $("#gallery").css({'float':'right','margin':'0px'});
      }
  if(e.target.id=="learn")
  {
    $("#home").css({'float':'right','margin':'0px'});
    $("#learn").css({'float':'left','margin':'0px'});
    $("#gallery").css({'float':'right','margin':'0px'});
  }
  if(e.target.id=="gallery")
  {
    $("#home").css({'float':'right','margin':'0px'});
    $("#learn").css({'float':'right','margin':'0px'});
    $("#gallery").css({'float':'left','margin':'0px'});
  }
});

但这些工作没有任何动画,对上面的代码中的一些幻灯片或移动动画几乎没有帮助。谢谢:))

3 个答案:

答案 0 :(得分:1)

您可以使用jQuery的animate()函数为CSS代码的更改设置动画。这包括位置,不透明度,颜色等的变化。

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

答案 1 :(得分:1)

HI伙伴,试试这个,这将

$('#toolbar img').click(function(e){
   $(e.target).css({'float':'left','margin':'5px'});
});

答案 2 :(得分:1)

我知道你已经标记了一个作为答案,但这里有一个脚本和css一起做同样的事情但是有动画

edit: here is a jsfiddle link with the code in action

#toolbar{
    position: relative;
    text-align:right;
    margin: 0 auto;
    width: 1257px;
    height: 60px;
    border:1px solid #000000;
}

#toolbar img{
    position:absolute;
}

    var movedImg;
positionImages();
function positionImages(){
    var rightPos = 0;
    $("#toolbar img").each(function(){
        $(this).css("right", rightPos);
        rightPos += $(this).width() + 5;
    });
}

$("#toolbar img").click(function() {
    if(movedImg){
        var rightPos = parseInt($(this).css("right"));
        movedImg.animate({"right" : rightPos}, "slow");
    }
    $(this).css("left","0");
    $(this).animate({"right" : "+=100%"}, "slow");
    movedImg = $(this);
});