简体   繁体   中英

Slide div (left to right) from 'behind' a button using jQuery

Using the last example of this guide ( http://www.learningjquery.com/2009/02/slide-elements-in-different-directions ), I am trying to get a div to toggle 'behind' a button.

Desired Result Example: 在此处输入图片说明 Initially the div including input fields, Button B, and Button C will be hidden. When 'Slide it' button is clicked, the div slides in FROM behind the button until a specific distance (margin) is met between the RIGHT side of the div and the 'Slide it' button. Upon clicking the button again (and/or when 'Esc' key is pressed), the div will slide "into" the button.

Here is the script, followed by the demo:

$('#button1').click(function() {
    var $marginRighty = $('.inner');
    $marginRighty.animate({
        marginRight: parseInt(
            $marginRighty.css('marginRight'),10) == 0 ?
                $marginRighty.outerWidth() : 0});
});

https://jsfiddle.net/ishq786/xqb5a7dq/

Fiddle .

I've solved some of your problems. I confess I'm not exactly sure how you want the outcome to look so I'll leave the tweaking to you. But two main things;

  1. I have used css to get one on top of the other. I positioned the inner div 100% right, position: relative , and the button over the top now has its parent div set from the right with position: absolute so that it can overlap with no footprint. I literally moved the button lower in the HTML so I didn't have to mess about with z-index, haha.
  2. I moved your Javascript into a separate function so you can call that with a keypress or however you like. This means you won't have code duplication.

Fiddle: https://jsfiddle.net/xqb5a7dq/6/

 $('#button1').on('click', function() { animateDiv(); }) $(document).keyup(function(e) { if (e.keyCode === 27 && $('.inner').hasClass('visible')) { animateDiv(); } }) function animateDiv () { $('.inner').toggleClass('visible'); $('.inner').animate({ width: 'toggle', },350); } 
 .toolbar { width: 100%; display: inline-block; overflow: hidden; white-space: nowrap; margin: 0px auto; padding: 5px 0px; background-color: skyblue; } #divA, #divB { display: inline; } .inner { float: right; display: none; padding-right: 20px; } #button1 { float: right; margin-right: 5px; } input, button { padding: 5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='toolbar'> <div> <button id="button1">Slide it</button> </div> <div class="inner is-hidden"> <div id="divA"> <input type="text" /> <input type="password" /> </div> <div id="divB"> <button>Button B</button> <button>Button C</button> </div> </div> </div> 

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