简体   繁体   中英

position div with auto width left of screen

Note: this css in snippet does not exactly equal my setup (I have fixed div in body) but otherwise its the same effect. I have div with auto width (text inside), which opens from the left. I want to close it such that it animates to left to its full width minus 50px. This works well when screen width is bigger then element width, but when its smaller, my element is already squished, so when I do calculation on button click, the width is not correct and when I animate out, it doesn't get to desired position (because it expand to its natural width as it gets more space going to the left).

How do I solve this?

 var b = $('.b') document.querySelector('#toggle').addEventListener('click', function() { var w = b.outerWidth(true), pos = w - 50 console.log(w) b.stop().animate({ 'left': -pos + 'px' }, { duration: 350 }); })
 .a { border: 1px solid #333; width: 200px; position: relative; }.b { background: #ddd; max-width: 300px; padding: 50px; text-align: center; position: absolute; } #toggle { position: absolute; left: 400px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="a"> <div class="b"> <div class="t">Lorem ipsum dolor sit amet</div> <div class="t">Ut laoreet hendrerit mi.</div> <div class="t">Lorem ipsum dolor sit amet</div> </div> </div> <a href="#" id="toggle">toggle</a>

  • Don't use jQuery
  • Use CSS and transform translate , and transition for the desired animation
  • Use JS's Element.classList.toggle() to toggle a desired CSS class that will transition the element from X -100% to X 0

 const EL = (sel, par) => (par||document).querySelector(sel); EL("#toggle").addEventListener("click", () => { EL("#menu").classList.toggle("is-open"); });
 /* QuickReset */ * {margin: 0; box-sizing: border-box; } #toggle { position: fixed; right: 0; /* hopefully you know how to style a Button */ } #menu { position: fixed; padding: 30px; width: calc(100vw - 100px); /* or whatever you want, does not matters */ height: 100vh; background: gold; transition: transform 0.5s; /* transition property and duration */ transform: translateX(-100%); /* -100% of self-width (hidden) */ } #menu.is-open { transform: translateX(0%); /* (visible) */ }
 <div id="menu">I am something that actually toggles</div> <button type="button" id="toggle">Toggle</button>

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