简体   繁体   English

从一个角落到另一个角落的对角线动画

[英]Animating a diagonal line from corner to corner

I am trying to animate a diagonal line across the page from one corner to another.我正在尝试将页面上的对角线从一个角移动到另一个角。 The line should be diagonal no matter the format of the screen.无论屏幕的格式如何,这条线都应该是对角线。 I figured (or so I think) that I have to use transform: rotate() in CSS.我认为(或者我认为)我必须在 CSS 中使用transform: rotate() Using jquery or Javascript, I tried returning and calculating the degree at which the line has to rotate for the given screen format.使用 jquery 或 Javascript,我尝试返回并计算给定屏幕格式的线条必须旋转的度数。 That argument should be passed to rotate() .该参数应传递给rotate()

I've tried the following with jQuery and Javascript:我用 jQuery 和 Javascript 尝试了以下操作:

<script>

  $('#move').css('transform', 'rotate(-' + Math.atan2($(window).width(), $(window).height()) + 'rad)').show();

</script>

or或者

<script>

  document.querySelector('#move').style.transform = Math.atan2($(window).width(), $(window).height())+'rad';

</script>

And with CSS and HTML:并使用 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>

The code draws a line across the screen, but it is not rotated.代码在屏幕上画了一条线,但没有旋转。 How can that be fixed?这怎么能解决?

You have to put your <script> to the very bottom of <body> , so the code works after your DOM is loaded.您必须将<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM