微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过在文本字段中输入数字来切换 CSS 样式条件Javascript?

如何解决通过在文本字段中输入数字来切换 CSS 样式条件Javascript?

我绝对需要社区中一些聪明人的帮助!

我用 HTML 和 CSS 创建了一个模拟时钟,现在想要使用输入掩码使时钟指针可移动。

举个例子:

我在小时的输入掩码中输入数字 11。 (晚上 11 点)。 CSS 类“.hourhand”现在应该相应地调整旋转(-30 度)。 1-12 相同,具有不同的旋转设置。

我现在已经使用了很多 Javascript 三天,但从未得到过全面的结果...... 代码也应该尽可能干净。也许通过 if & else?我只是一个绝对的 javascript 初学者......

非常感谢您的帮助!

解决方法

可以通过注意 0 小时或 12 小时的度数为 0 并且两者之间的值的数量来确定以度数旋转的手的位置:

(hours / 12) * 360 degrees

您可能想要检查用户是否输入了 0 到 12 之间的值 - 此代码段简化了事情,只需要输入 mod 12 的值:

const hourhand = document.querySelector('.hourhand');
const update = document.querySelector('.update');
const input = document.querySelector('.input');

update.addEventListener('click',function () {
  hourhand.style.setProperty('--degrees',(input.value%12 / 12) * 360);
});
.hourhand {
  --degrees: 0; /* this will get changed with Javascript */
  transform: rotate(calc(var(--degrees) * 1deg));
  transform-origin: 50% 100%; /* the bottom of the hour hand */ 
  
  position: relative;
  left: 10vmin;
  rtop: 10vmin;
  width: 1vmin;
  height: 20vmin;
  background-color: black;
  margin: 5vmin;
}
<input class="input" type="number"/>
<button class="update">Click me to update the hand</button>
<div class="hourhand"></div>

,

你真棒!!!!

它工作正常。但现在我在思考上犯了一个愚蠢的错误。如果我添加分针,则小时必须获得适当的旋转角度。换句话说,在下午 1:30小时显示应在下午 1:00 之间。下午 2:00 ...我如何在适当的 .style.setProperty 中输入它?

我已经非常感谢你了!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。