更改innerHTML时,绝对元素的位置也会改变

时间:2018-12-20 15:20:55

标签: javascript css

我有一个绝对位于div内的按钮,当单击此按钮并更改innerHTML(以模拟播放按钮)时,按钮的位置将移动。我相信这是旋转转换的问题。我该如何解决,使按钮不动?任何帮助将不胜感激。

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>

2 个答案:

答案 0 :(得分:2)

这与宽度有关-由于暂停时间比播放时间长,因此变换原点会有所不同(默认是从中间开始)。要解决此问题,您可以为按钮设置固定宽度:

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

答案 1 :(得分:2)

调整转换的原点以及如下所示的转换,您的按钮将简单地增大而不会移动:

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>