javascript - 让 div 顶部位置每 x 秒更改一次

标签 javascript jquery html css

我有一个带 child 的绝对定位的 div。我希望这个 div 的最高位置每 x 秒改变一次。我试过使用 jquery setInterval 但它只更改一次。下面是我的代码。

.com_prices {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #dd0d0d;
  position: relative;
} 
.com_tabs {
  position: absolute;
  height: auto;
  width: 100%;
}
.com_price_tab {
  width: 90%;
  margin: 10px auto;
  height: 100px;
  background: #fff; 
}

html

<div class="com_prices">
    <div class="com_tabs">
      <div class="com_price_tab"></div>
      <div style="background: #28bc88" class="com_price_tab"></div>
      <div style="background: #fff000" class="com_price_tab"></div>
      <div style="background: #333" class="com_price_tab"></div>
      <div style="background: #28bc88" class="com_price_tab"></div>
      <div style="background: #999" class="com_price_tab"></div>
      <div class="com_price_tab"></div>
      <div class="com_price_tab"></div>
    </div>
  </div>

脚本

 setInterval(function() {
    $('.com_tabs').animate({top: "-100px"}, 350);
 }, 2000);

最佳答案

您将 top 设置为“-100px”。您需要将当前位置减去 100。

 var $comtabs = $('.com_tabs');
 setInterval(function() {
    var top = parseInt($comtabs.css("top"));
    $comtabs.animate({top: top - 100 + "px"}, 350);
 }, 2000);

工作示例:

var $comtabs = $('.com_tabs');
setInterval(function() {
  var top = parseInt($comtabs.css("top"));
  $comtabs.animate({
    top: top - 100 + "px"
  }, 350);
}, 2000);
html,
body {
  background: #000;
  height: 100%;
  margin: 0;
  padding: 0;
}

.com_prices {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #dd0d0d;
  position: relative;
}

.com_tabs {
  position: absolute;
  height: auto;
  width: 100%;
}

.com_price_tab {
  width: 90%;
  margin: 10px auto;
  height: 100px;
  background: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="com_prices">
  <div class="com_tabs">
    <div class="com_price_tab"></div>
    <div style="background: #28bc88" class="com_price_tab"></div>
    <div style="background: #fff000" class="com_price_tab"></div>
    <div style="background: #333" class="com_price_tab"></div>
    <div style="background: #28bc88" class="com_price_tab"></div>
    <div style="background: #999" class="com_price_tab"></div>
    <div class="com_price_tab"></div>
    <div class="com_price_tab"></div>
  </div>
</div>

关于javascript - 让 div 顶部位置每 x 秒更改一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45107984/

相关文章:

javascript - 选择孙子 onclick 事件

对象中未填充 Javascript 键

javascript - 如何使用 Javascript 触发附加到 DOM 的元素上的 CSS3 转换?

javascript - jQuery 更改包含元素的宽度与幻灯片

html - 网格中的图像和中心的描述

javascript - 为什么 'NaN' 和 'Undefined' 不是 JavaScript 中的保留关键字?

JavaScript - 禁用互联网连接

jquery - Twitter Bootstrap slider 默认值

php/css/html 语言按钮当前语言

javascript - linter 和验证器有什么区别?