【问题标题】:How to rotate darkmode/lightmode button more than once using Javascript如何使用 Javascript 多次旋转暗模式/亮模式按钮
【发布时间】:2020-08-05 21:43:06
【问题描述】:

我正在尝试设置一个带有图像背景的 div 作为暗模式/白天模式的选择器。唯一的问题似乎是如何在点击时将图像旋转 180 度,以便在选择暗模式时显示白天,而在选择亮模式时将其旋转 180 度到夜空。

我的 HTML: <div id="selector" class="selector"></div>

CSS(bg 图像是一个圆圈。太阳和太阳在左边。月亮和星星在右边。:

height: 3rem;
  width: 3rem;
  border: 1px solid lightgrey;
  margin: 5rem auto;
  background-image: url('https://cdn1.vectorstock.com/i/1000x1000/32/25/day-and-night-icon-isolated-on-background-vector-21083225.jpg');
  background-size: 120%;
  background-repeat: no-repeat;
  background-position: center, center;
  border-radius: 50%;
  /* rotate 90deg sets the background image with the night sky on top part of the image*/
 transform: rotate(-90deg); 
  cursor: pointer;

90 度旋转将带有黑暗天空的图像置于顶部(ergo:准备好选择黑暗模式)。

JS:

const elem = document.getElementById('selector');
elem.addEventListener('click', spin);
function spin() {
  elem.style.transform = "rotate(180deg)";
}

在第一次点击图像时,它会将 div 旋转 180 度,但基于其原始位置而不是使用 CSS 完成的 90 度旋转。我可以解决这个问题。问题是任何后续单击图像将不再旋转它,因为该元素的变换属性已经是rotate(180deg);

【问题讨论】:

  • 将角度存储在外部作用域的一个变量中,每点击一次按钮就增加180,然后使用该变量创建transform的值。

标签: javascript animation transform rotatetransform


【解决方案1】:

对于第一次旋转,旋转 90 度。然后每个后续的点击都从上一次点击旋转 180 度,使用外部范围内的变量。

通过使用 deg = (deg + 180) % 360 您将变量保持在 90 和 270 之间交替。270 度旋转与您的 -90 度初始旋转相同。

const elem = document.getElementById('selector');
elem.addEventListener('click', spin);
var deg = 90
function spin() {
  elem.style.transform = `rotate(${deg}deg)`;
  deg = (deg + 180) % 360
}
.selector {
  height: 3rem;
  width: 3rem;
  border: 1px solid lightgrey;
  margin: 5rem auto;
  background-image: url('https://cdn1.vectorstock.com/i/1000x1000/32/25/day-and-night-icon-isolated-on-background-vector-21083225.jpg');
  background-size: 120%;
  background-repeat: no-repeat;
  background-position: center, center;
  border-radius: 50%;
  /* rotate 90deg sets the background image with the night sky on top part of the image*/
 transform: rotate(-90deg); 
  cursor: pointer;
}
<div id="selector" class="selector" style='background-image: url("https://cdn1.vectorstock.com/i/1000x1000/32/25/day-and-night-icon-isolated-on-background-vector-21083225.jpg")'></div>

【讨论】:

  • 非常感谢!这是完美的。
猜你喜欢
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 2022-12-15
  • 2020-11-21
  • 1970-01-01
  • 2021-12-30
  • 2023-02-10
相关资源
最近更新 更多