我编写了一些代码,允许我使用css3在点击时添加背景图像移动的过渡。我的代码说“点击添加874px到背景位置的x值”。这完全有效,直到我在项目上添加我的过渡,因为它允许用户在过渡期间点击,这会破坏我的场景。我只希望用户查看874px的倍数。有没有更好的方法可以做到这一点而不是超时?我希望用户能够多次点击,但只能达到最近的874px倍数。
希望这有点道理。感谢您的任何帮助。 JSFIDDLE DEMO
HTML
<div class="container">
<div class="decoration two"></div>
<div class="decoration one"></div>
<span id="btnPrev" class="prev">prev</span>
<span id="btnNext" class="next">next</span>
</div>
JS
var btnPrev = $("#btnPrev");
var btnNext = $("#btnNext");
var decorationOne =$(".decoration.one");
var decorationTwo =$(".decoration.two");
$(function () {
btnNext.click(function() {
var DOG = decorationOne.css('background-position');
var splat = DOG.replace(/[^-\d\. ]/g, '').split(" ");
var new_values = [parseFloat(splat[0]) - 874 + "px", parseFloat(splat[1]) + 0 +"px"]; // x, y
decorationOne.css('background-position', new_values.join(" "));
});
btnPrev.click(function() {
var DOG = decorationOne.css('background-position');
var splat = DOG.replace(/[^-\d\. ]/g, '').split(" ");
var new_values = [parseFloat(splat[0]) + 874 + "px", parseFloat(splat[1]) + 0 +"px"]; // x, y
decorationOne.css('background-position', new_values.join(" "));
});
});
CSS
.container {
background: none repeat scroll 0 0 #E7F3FF;
border: 4px solid blue;
border-radius: 16px 16px 16px 16px;
box-shadow: 0 2px 2px rgba(1, 1, 1, 0.2);
color: #054B98;
height: 400px;
margin: 35px 0 15px;
overflow: hidden;
position: relative;
width: 874px;
}
.decoration {
position: absolute;
}
.decoration.one {
background: url("http://s22.postimg.org/ljly8r7tr/hills_1.png") repeat scroll left 0 transparent;
bottom: 0;
height: 500px;
-webkit-transition: background-position 1s ease 0s;
-moz-transition: background-position 1s ease 0s;
transition: background-position 1s ease 0s;
width: 2622px;
}
.decoration.two {
background: blue;
bottom: -180px;
height: 472px;
width: 5760px;
}
.prev {
position: absolute;
top: 50%;
left: 20px;
}
.next {
position: absolute;
top: 50%;
right: 20px;
}
答案 0 :(得分:1)
我会使用animationend
事件(MDN https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations#Adding_the_animation_event_listeners)。基本上在启动动画时设置var true,然后在animaitonend
事件将其设置为false之前不再执行
我误解了。您可以维护索引变量并基于该变量进行计算,而不是使用可能处于转换中期的当前background-position
值。点击事件始终可以访问索引变量,即使它们从现在起20分钟后也会发生。
var btnPrev = $("#btnPrev");
var btnNext = $("#btnNext");
var decorationOne =$(".decoration.one");
var decorationTwo =$(".decoration.two");
$(function () {
var index = 0;
btnNext.click(function() {
index = index + 1; //you'll also probably want to check it's not over a max
decorationOne.css('background-position', (index * 874) + 'px 0px'); //assuming y is always 0
});
btnPrev.click(function() {
index = index - 1; //you'll also probably want to check it's not under 0
decorationOne.css('background-position', (index * 874) + 'px 0px'); //assuming
});
});