javascript - 从一个角落到另一个角落的对角线动画
问题描述
我正在尝试将页面上的对角线从一个角移动到另一个角。无论屏幕的格式如何,这条线都应该是对角线。我认为(或者我认为)我必须transform: rotate()
在 CSS 中使用。使用 jquery 或 Javascript,我尝试返回并计算给定屏幕格式的线条必须旋转的度数。该参数应传递给rotate()
.
我用 jQuery 和 Javascript 尝试了以下方法:
<script>
$('#move').css('transform', 'rotate(-' + Math.atan2($(window).width(), $(window).height()) + 'rad)').show();
</script>
或者
<script>
document.querySelector('#move').style.transform = Math.atan2($(window).width(), $(window).height())+'rad';
</script>
并使用 CSS 和 HTML:
<style>
#move {
width: 0;
height: 4px;
background: red;
position: relative;
animation: mymove 3s;
animation-fill-mode: forwards;
transform-origin: top left;
}
@keyframes mymove {
from {top: 0; transform: rotate(0deg);}
to {width:100%; background-color: blue;}
}
</style>
<body>
<div id="move"></div>
</body>
代码在屏幕上画了一条线,但没有旋转。这怎么能解决?
解决方案
你必须把你放在<script>
最底层<body>
,这样代码在你的 DOM 加载后才能工作。
const move = document.querySelector('#move')
const angle = Math.atan2(document.documentElement.clientHeight, document.documentElement.clientWidth);
const width = document.documentElement.clientWidth / Math.cos(angle);
move.style.setProperty('--a', angle + 'rad');
move.style.setProperty('--w', width + 'px');
html, body, #move {margin:0; padding:0}
#move {
width: 0;
height: 4px;
background: red;
position: relative;
animation: mymove 3s;
animation-fill-mode: forwards;
transform: rotate(var(--a));
transform-origin: top left;
}
@keyframes mymove {
to {
width: var(--w);
background-color: blue;
}
}
<div id="move"></div>
推荐阅读
- c# - Azure 管道绑定到 localhost 以进行测试
- angular - Angular HttpInterceptor ngOnDestroy 生命周期钩子
- php - 我可以用图像的奇异值训练神经网络吗?
- swift - 如果 Button 具有 buttonStyle,则 SwiftUI 的键盘快捷键不起作用
- sed - 在文本和模式之间进行 sed 条件插入
- flexmark - Markdown 到 docx 的转换
- java - 通过使用 Java Stream API 组合来自 int 数组的唯一值来生成最小 int 值
- python - Numpy.shape 元组 - 元素的顺序
- c++ - 返回二维向量中索引 i,j 的所有组合,总和为所需值
- java - 创建 com.linecorp.armeria.spring.ArmeriaAutoConfiguration 中定义的名称为“armeriaServer”的 bean 时出错