简体   繁体   中英

How can I make this div slide across half of the screen?

I am trying to build some responsive javascript code that will make this div slide across half of the screen.

I am able to make this div move across 'x' amount of the screen but I am unsure how to make it responsive.. I would love some guidance. I think my main problem is I don't know what 'units' javascript moves in..

Any help would be greatly appreciate. I am still trying to learn!

 var div = document.getElementById("slidingDiv"); div.style.position = "absolute"; var left = document.body.offsetWidth; div.style.left = left + "px"; var gap = 3; var timer = window.setInterval(function() { div.style.left = left + "px"; if (left - gap < 40) { left = 0; } else { left -= gap; } if (left == 0) { clearInterval(timer); } }, 1);
 <div id="slidingDiv">Move me!</div>

Looking at the "if (left - gap < 40)..... I want the '40' to basically be half the width of the screen.

Is this possible?

You don't need JavaScript for this. Instead, use CSS animations.

 /* Animation to have any absolute element go from the right to left center */ @keyframes slide-from-left { from { left: 100%; } to { left: 50%; } } /* Element to be moved. Must have position: absolute */.slide-left { position: absolute; left: 50%; transform: translateX(-50%); animation-name: slide-from-left; animation-duration: 2s; }
 <body> <div class="slide-left">Fancy div!</div> </body>

Edit:

It looks like you want it to run on scroll. This is not currently possible with CSS 3, so you will have to use partial JavaScript. If JavaScript is disabled, the element should default to the center.

 // Sets element to right by default if JavaScript enabled, otherwise element is by default animated document.getElementsByClassName("element")[0].className = "element hide-to-right"; // If scroll and scroll height is more than 50% of window height, add the slide-in class, making the div move window.onscroll = function() { if (window.scrollY > window.innerHeight/2) { document.getElementsByClassName("element")[0].className = "element slide-in"; } }
 @keyframes slide-from-left { from { left: 100%; transform: translateX(-50%); } to { left: 50%; transform: translateX(-50%); } }.element { position: absolute; left: 50%; transform: translateX(-50%); }.hide-to-right { left: 100%; transform: translateX(-50%); }.slide-in { animation-name: slide-from-left; animation-duration: 2s; }
 <body> <div style="height:100vh;">Content, scroll down...</div> <div class="element">Fancy div:</div> <div style="height;100vh;"></div> </body>

You can use (window.innerWidth / 2) to get half the width of the screen.

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