【问题标题】:How can I make two divs of the same class move across the screen?如何使同一类的两个 div 在屏幕上移动?
【发布时间】:2016-03-29 05:56:35
【问题描述】:

我希望某些 div 在 Javascript 中在屏幕上移动,有点像 this website(向下滚动),只是水平方向,或者像 here(也是垂直方向,但我喜欢水平方向)

这是我的 HTML:

<div id = "creators" class = "big-part">
    <h3>Creators</h3>
    <div class = "creator_name">
        <h4>Name</h4>
        <p>Text</p>
    </div>
    <div class = "creator_name">
        <h4>Name</h4>
        <p>Text</p>
    </div>
    <div class = "creator_name">
        <h4>Name</h4>
        <p>Text</p> 
    </div>
</div>

我的 CSS:

.big-part {
    color: rgb(230, 230, 230);
    background-color: #3c3c91;
    border-radius: 21px;
    padding: 0.5% 1.5%; 
    margin-top: 2%;
}
.creator_name {
    background-color: rgb(230, 230, 230);
    height: 300px;
    color: #3c3c91;
    border-radius: 15px;
    padding: 1%;
}
.creator_name {
    width: 25%;
    display: inline-block;
    margin: 2% 2%;
}

还有我在script 标签中的javascript:

var creatorEl= document.getElementsByClassName("creator_name");

var startTime = new Date().getTime();
var moveTheDiv = function() {
    var currTime = new Date().getTime();
    var secondsElapsed = ((currTime - startTime)/1000);
    var newLeft = parseFloat(secondsElapsed) * 30 + "px";
    creatorEl.style.left = newLeft;
    window.requestAnimationFrame(walkTheCat);
};
moveTheDiv();

谢谢!

顺便说一句,这个动画只有在客户端/用户向下滚动并且 div 可见时才会发生。 如果你愿意,你可以回答一半的问题,我会帮忙的。

编辑: 只有给每个人添加一个 ID 并使用 ID 移动它们,我才能让它们移动,有没有办法同时移动它们但只使用一个类?

【问题讨论】:

  • 您在寻找一些视差滚动插件吗?
  • 不,只是一个移动的 div
  • 你的当前代码有什么问题?
  • 在jquery animate下查看
  • 您看到getElementsByClassName 的工作原理了吗? . .它将返回具有指定类的所有元素的集合..因此您应该在将其定位为移动之前过滤这些元素

标签: javascript jquery html css animation


【解决方案1】:

您可能会发现动画引擎 Velocity.js 很有帮助。 http://julian.com/research/velocity/(我不隶属于创作者)。

您实现的功能类似于 jQuery 的 .animate() 方法。

这是一个如何旋转 div 的示例:

$(document).ready(function(){   
   $('#divToAnimate').velocity(
    { rotateX: "+=0", 
      rotateY: "+=360",
      height: '+=50px',
      width: '+=100px'
    }, 
    {
      duration:4000,
      loop:false,
      easing:'linear'
  });
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Sample animation with Velocity.js</title>

  <!-- jQuery CDN -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
  </script>

  <!-- Velocity.js CDN -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js"></script>
</head>

<body>
  <div id="divToAnimate">Example Div to Animate</div>
</body>

</html>

希望对您有所帮助,祝您好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多