首页 > 解决方案 > 从一个角落到另一个角落的对角线动画

问题描述

我正在尝试将页面上的对角线从一个角移动到另一个角。无论屏幕的格式如何,这条线都应该是对角线。我认为(或者我认为)我必须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>

代码在屏幕上画了一条线,但没有旋转。这怎么能解决?

标签: javascriptjqueryhtmlcss

解决方案


你必须把你放在<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>


推荐阅读