Javascript move div onClick

夙愿已清 提交于 2020-01-03 05:34:16

问题


I'm trying to get a div #sidebar that rests above my main #stream div to move from position left: 565px; to position left: 0px; onClick of one image in the #sidebar div (the red arrow in the images below), and do the reverse onClick of the same image. I know I have to use JavaScript, but I have no idea what the code would be. If possible, I would like to animate the div move too.

The pre-clicked state (the arrow will be my link):

The post-clicked state:

Thanks in advance!


回答1:


If you want to animate it using animate have a look at this. It should get you pointed in the right direction:

http://jsfiddle.net/3DpfJ/5/embedded/result/ - Full screen result

http://jsfiddle.net/3DpfJ/5/ - source code

So what I simply did was this:

$(function()
{
  var expanded = false;
  $('#sidebar').click(function()
                      {
                          if (!expanded)
                          {
                              $(this).animate({'left' : '0px'}, {duration : 400});
                              expanded = true;
                          }
                          else
                          {
                             $(this).animate({'left' : '565px'}, {duration: 400});
                              expanded = false;
                          }
                      });
 });

This is probably the simplest way of doing it via animation. Duration is set to 400 so it will take 0.4 seconds to animate. Adjust as you please.

This script should be executed as soon as you load the page to ensure that the expand works. You will want to create <script type="text/javascript"></script> tag in the header and put the code there.

Hope it works for you.




回答2:


$('#sidebar').click(function(){
    $(this).animate({"left": "0"});
});



回答3:


jquery uses toggle to handle this. It works better than a regular "animate" because it combines the hide and show into one function (toggle).

You might need to do some tweaking to fit your needs but this should get you started:http://jqueryui.com/toggle/



来源:https://stackoverflow.com/questions/15038989/javascript-move-div-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!