我有一个带 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/