简体   繁体   中英

Position of absolute element changes when innerHTML is changed

I have a button that is absolutely positioned within a div, when this button is clicked and the innerHTML changed (to simulate a play button), the position of the button moves. I believe this is a problem with the rotation transformation. How could I solve this so the button does not move? Any help would be greatly appreciated.

 const playButton = document.querySelector('#play'); let paused = false; playButton.addEventListener("click", function() { if (paused == true) { playButton.innerHTML = "Pause"; paused = false; } else { playButton.innerHTML = "Play"; paused = true; } }); 
 #outer { background-color: green; height: 100vh; width: 100vw; position: relative; } #play { position: absolute; top: 50%; transform: translateY(-50%) rotate(-90deg); } 
 <div id="outer"> <button id="play">Play</button> </div> 

This is to do with the width - as pause is longer than play, the transform origin will be different (it's default is to start in the centre). To solve this, you could give the button a fixed width:

 const playButton = document.querySelector('#play'); let paused = false; playButton.addEventListener("click", function() { if (paused == true) { playButton.innerHTML = "Pause"; paused = false; } else { playButton.innerHTML = "Play"; paused = true; } }); 
 #outer { background-color: green; height: 100vh; width: 100vw; position: relative; } #play { position: absolute; top: 50%; width: 5em; text-align: center; transform: translateY(-50%) rotate(-90deg); } 
 <div id="outer"> <button id="play">Play</button> </div> 

More information about transform origin

Adjust the origin of the transformation and also the transformation like below and your button will simply grow without moving:

 const playButton = document.querySelector('#play'); let paused = false; playButton.addEventListener("click", function() { if (paused == true) { playButton.innerHTML = "Pause"; paused = false; } else { playButton.innerHTML = "Play"; paused = true; } }); 
 #outer { background-color: green; height: 100vh; width: 100vw; position: relative; } #play { position: absolute; top: 50%; transform-origin:left center; transform: rotate(-90deg) translateY(100%) ; } 
 <div id="outer"> <button id="play">Play</button> </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