简体   繁体   中英

How to make a div slide to the bottom of a window on event

I am trying to make a div slide to a FIXED position on the bottom of my screen temporarily, when I click on a button. I want it to slide back to where it was on the button release, but I can't quite get it to work. My code is the following

$("#chatContainer").css("position", "fixed");
$("#chatContainer").animate({ top: '60%' }, 'slow');  

Because the position is fixed temporarily, the Div pops up from the middle of the screen and then slides down. I would like it to slide from the bottom and stick there until release of the click.

Here's the way I would try it (off the top of my head):

  1. Get the window x/y coordinates of the container in question.
  2. $.clone it, then set the x/y coordinates of the clone to the same as the original (that way it appears to be moving FROM the original location).
  3. Perform necessary animation (hide original > animate clone to new location > re-show original in new position > fade out / delete clone)

You might need to make some tweaks to avoid unnecessary binding etc. on the clone, since the clone is "just for show".

I'm not sure this is the "best" way technically, but it is the approach I would try to take to get the desired user experience.

This code assumes that your sliding div is within a container, but it should be easily adjustable to use the browser window as a reference:

var speed = .5; // higher number = faster animation
var originalPosition = null;

$('#container').mousedown(function(){
    var $slider = $('#slider');
    var start = $slider.position().top;
    if(!originalPosition) {
        originalPosition = {top: start};
    }
    var end = $(this).height() - $slider.height();
    var duration = (2/speed) * (end - start);
    $slider.css({
        position: 'absolute',
        top: start+'px',
    }).stop().animate({
        top: end+'px'
    },duration);
}).mouseup(function(){
    var $slider = $('#slider');
    $slider.stop();
    var start = $slider.position().top;
    var end = originalPosition.top;
    var duration = (2/speed) * (start - end);
    $slider.animate({
        top: end+'px'
    },duration,function(){
        $(this).css({position: 'static'});
    });
});

Here's an example: jsFiddle: DEMO

This solution has the benefit of adjusting the duration of the animation based on how far the div needs to slide. This way, the 'speed' of the animation is constant.

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