带有setInteval函数的非常简单的滑块。如果这种情况有一些规则,请告诉我。我有5张幻灯片,其中只有3张显示,然后滑块转到" margin-left" =" 0"位置,没有显示最后2张幻灯片。 我在我的代码中写入以返回" margin-left" =" 0"只有在" margin-left"达到" 2000px"或者更多(每张幻灯片是500px,我有5张幻灯片)。 换句话说,滑块在达到" 1000px" " margin",虽然我写了" 2000px"或更多。
我的HTML是 500px< div&gt ;; 2500px< ul>里面< div&gt ;; 5件500px< 5件li>里面< ul>,我不使用overflow:hidden来显示会发生什么。
<style>
#container {
height: 400px;
border: 4px solid red;
}
#container ul {
list-style-type: none;
height: 100%;
padding: 0px;
display: flex;
transition: all 1s ease
}
#container ul li {
width: 100%;
height: 100%
}
#container ul li:nth-child(1) {
background-color: yellow;
opacity: 0.5;
}
#container ul li:nth-child(2) {
background-color: green;
opacity: 0.5
}
#container ul li:nth-child(3) {
background-color: red;
opacity: 0.5
}
#container ul li:nth-child(4) {
background-color: teal;
opacity: 0.5
}
#container ul li:nth-child(5) {
background-color: grey;
opacity: 0.5
}
</style>
<body>
<div id="container" style="width:500px;">
<ul style="margin:0px; width:2500px;">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</body>
Javascript方面:
<script>
ul_list = document.getElementsByTagName("ul")[0];
li_list = document.getElementsByTagName("li");
li_width = parseFloat(document.getElementById("container").style.width);
el_width = li_width;
li_array = Array.prototype.slice.call(li_list, 0);
function carousel() {
/*THIS IS MY PROBLEM, return to marginLeft = 0 when marginLeft = -2000px or more,
in reality it executes if statement when -1000px is reached*/
if (ul_list.style.marginLeft <= -((li_width * li_array.length) - li_width) + "px") {
ul_list.style.marginLeft = 0 + "px";
el_width = li_width;
}
else {
ul_list.style.marginLeft = -el_width + "px";
el_width += li_width;
}
}
function call() {
call_carousel = setInterval(carousel, 3000);
}
call();
</script>
答案 0 :(得分:0)
你的逻辑不起作用,因为&#34; .marginLeft&#34; call是一个字符串。
试试这个:
var ulMarginLeft = parseInt(ul_list.style.marginLeft);
答案 1 :(得分:0)
添加一个新的实用程序功能,如:
function getInt(value) {
return parseInt(value.match(/\d+/)[0]);
}
然后修改比较,如:
var marginLeft = getInt(ul_list.style.marginLeft);
var arrayMargin = getInt((li_width * li_array.length) - li_width) * -1;
// Check the values once in console for debugging
console.log( marginLeft, arrayMargin)
if (marginLeft <= arrayMargin ) {
// Your code here....
}