javascript - 使用 JavaScript 的 CSS 动画

标签 javascript css

我刚开始学习 JavaScript,正在尝试制作一个模拟时钟。首先,我用 CSS 创建了第二个仪表。然后我试图将它转换成 JavaScript。我不想为此使用任何 jQuery 或任何其他 JS 框架。

如何在 JavaScript 中设置 css @keyframe?这是我的 CSS 代码:

.second{
  height: 5px;
  width: 180px;
  background-color: #aaaaaa;
  border-radius: 5px;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-animation-name: spin;
  -webkit-animation-duration: 60s;
  -webkit-animation-iteration-count: infinite;
  -webkit-animation-timing-function: linear;
  -o-transition: rotate(360deg);
  transform-origin: left center;
  z-index: 3;
}

@keyframes spin {
    from {transform:rotate(0deg);}
    to {transform:rotate(360deg);}
}

这个css的js代码

var second = document.querySelector(".second");
      second.style.height = "5px";
      second.style.width = "180px";
      second.style.backgroundColor = "#aaaaaa";
      second.style.borderRadius = "5px";
      second.style.position = "absolute";
      second.style.top = "50%";
      second.style.left = "50%";
      second.style.transformOrigin = "left center";
      second.style.zIndex = "3";

      second.style.webkitAnimationName = "Spin";
      second.style.webkitAnimationDuration = "60s";
      second.style.webkitAnimationIterationCount: "infinite"; //doesn't work
      second.style.webkitAnimationTimingFunction: "linear"; //doesn't work
      second.style.oTransition: "rotate(360deg)"; //doesn't work

最佳答案

这可以通过将所需的文本(@keyframes 旋转规则)附加到文档中的样式标签来轻松实现。我没有费心去检查它是否已经完成,所以单击多个按钮times 将多次附加规则。它至少需要 1 个样式标签才能运行,使用的标签是最后一个,最后,如果最后一个样式标签引用外部文件,这将失败。

要轻松避免这些限制,您可以简单地创建一个新的脚本元素并将其附加到 document.head 元素。您只需要设置一个标志或给标签一个类,以便您稍后可以找到它并避免添加两次。

function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}

function onStart()
{
	var styleTags = allByTag('style');
	var lastStyleElem = styleTags[ styleTags.length-1 ];
	
	var txt = '@keyframes spin {' + '\n';
		txt += ' from {transform:rotate(0deg);}' + '\n';
		txt += ' to {transform:rotate(360deg);}' + '\n';
		txt += '}' + '\n';
	lastStyleElem.innerHTML += txt;
}
.second{
  height: 5px;
  width: 180px;
  background-color: #aaaaaa;
  border-radius: 5px;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-animation-name: spin;
  -webkit-animation-duration: 60s;
  -webkit-animation-iteration-count: infinite;
  -webkit-animation-timing-function: linear;
  -o-transition: rotate(360deg);
  transform-origin: left center;
  z-index: 3;
}
<button onclick='onStart()'>Start transform</button>
<div class='second'></div>

关于javascript - 使用 JavaScript 的 CSS 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37965260/

相关文章:

javascript - 内联 require.js 文本!使用咕噜声

javascript - 如何获取 HTML 按钮的 textValue

javascript - HTML 和 CSS 更改整个网页上的日期格式

javascript - 如何在 React.js 中编辑多个元素的样式

javascript - 有没有办法在响应式幻灯片照片库的末尾添加文本内容?

html - 100% 宽度部分内的最后一列背景颜色

javascript - 如何不允许用户在带有选择选项的输入字段中输入值

javascript - 将浏览器元素中的 [value] 内容存储为字符串

jquery - 悬停可点击的图像描述不起作用

html - 将 div 置于 div 中