简体   繁体   中英

Javascript move div onClick

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!

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.

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM