我在将CSS属性设置为if语句的条件时遇到问题。
我的目标是在条件为真时重置特定div的值。例如,当.inline-grid
的left属性变为-200%或200%时,每次将left属性重置为0,这样就好像永远重复其中的内容。
因此,我尝试比较值之间的CSS属性,但是它不起作用。
真的很难弄清楚,因为浏览器不会在控制台面板上显示任何类型的错误消息。
这是我的代码。
* SOF预览运行我的代码时出错。您可以在CodePen中进行检查。
$(function swipeInit() {
/* Variables */
var _ = $('#swipe > .container > .grid > .inline-grid'),
myList = _.find('ul'),
myItem = myList.find('li'),
beforeClone = myItem.first().before(myItem.last().clone()),
afterClone = myItem.last().after(myItem.first().clone());
/* Actions */
var swipeAction = () => {
myList.animate({
left: '-=' + 100 + '%'
}, () => {
/* -- This part doesn't work -- */
if (myList.css('left') == (-200 + '%')) {
myList.css({
left: 500 + '%'
});
}
/* -- This part doesn't work -- */
});
}
swipeLoop = setInterval(() => {
swipeAction();
}, 2000);
/* Logs */
console.log(myList);
})
* {
margin: 0;
padding: 0;
}
ul li {
list-style: none;
}
#swipe {
}
.container {
width: 100%;
height: 100%;
display: flex;
flex-flow: row;
justify-content: center;
}
.grid {
position: relative;
width: 1170px;
height: 100%;
border: 1px dashed black;
}
.inline-grid {
position: relative;
width: 100%;
height: 100%;
}
.cell {
position: relative;
width: 100%;
height: 100%;
display: flex;
flex-flow: row;
justify-content: center;
}
._contents {
position: relative;
width: 100%;
height: 100%;
flex-shrink: 0;
}
<!-- Swipe -->
<section id="swipe">
<div class="container">
<div class="grid">
<div class="inline-grid">
<ul class="cell">
<li class="_contents">
<p>Test Swipe Title 1</p>
<p>consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</li>
<li class="_contents">
<p>Test Swipe Title 2</p>
<p>consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</li>
<li class="_contents">
<p>Test Swipe Title 3</p>
<p>consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</li>
</ul>
</div>
</div>
</div>
</section>
<!-- /end Swipe -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 0 :(得分:1)
您将必须获得width
中的ul
,并获得该值的-200%(以像素为单位)。然后,您将left
与得到的结果进行比较。
var ulWidth = myList.width()
if (parseInt(myList.css('left')) == parseInt(ulWidth * -2)) {
myList.css({
left: 100 + '%'
});
}
$(window).resize(function() {
ulWidth = myList.width();
});