【发布时间】:2016-04-15 05:38:18
【问题描述】:
如何更改此代码jsfiddle,以便在按下按钮时,弹跳的 div 立即停止在其轨道上?我有按钮和弹跳 div,但它们被设置为停止在特定位置。
HTML
<div class="bouncyHouse">
<button type="button">Click Me!</button>
<div class="bouncer" data-vx='2' data-vy='-3'>
<span>space</span>
</div>
<div class="bouncer" data-vx='-2' data-vy='2'>
<span>space</span>
</div>
<div class="bouncer" data-vx='5' data-vy='2'>
<span>space</span>
</div>
</div>
css
.bouncyHouse {
height: 200px;
width: 150%;
background-color: black;
position: relative;
}
.bouncer {
position: absolute;
width: 200px;
color: white;
}
.bouncer:nth-child(2) {
top: 30px;
left: 100px;
}
.bouncer:nth-child(3) {
top: 50px;
left: 200px;
}
javascript
function hitLR(el, bounding) {
console.log($(el).data('vx'), $(el).data('vy'))
if (el.offsetLeft <= 0 && $(el).data('vx') < 0) {
console.log('LEFT');
$(el).data('vx', -1 * $(el).data('vx'))
}
if ((el.offsetLeft + el.offsetWidth) >= bounding.offsetWidth) {
console.log('RIGHT');
$(el).data('vx', -1 * $(el).data('vx'));
}
if (el.offsetTop <= 0 && $(el).data('vy') < 0) {
console.log('TOP');
$(el).data('vy', -1 * $(el).data('vy'));
}
if ((el.offsetTop + el.offsetHeight) >= bounding.offsetHeight) {
console.log('BOTTOM');
$(el).data('vy', -1 * $(el).data('vy'));
}
}
function mover(el, bounding) {
hitLR(el, bounding);
el.style.left = el.offsetLeft + $(el).data('vx') + 'px';
el.style.top = el.offsetTop + $(el).data('vy') + 'px';
}
function moveIt() {
$('.bouncer').each(function() {
mover(this, $('.bouncyHouse')[0]);
});
};
$htmlBack = $('.bouncer').clone();
moveInterval = setInterval(moveIt, 50);
$('button').on('click', function(){
console.log(moveInterval);
if( moveInterval != 0){
clearInterval(moveInterval);
$('.bouncer').remove();
$('.bouncyHouse').eq(0).append($htmlBack);
$htmlBack = $('.bouncer').clone();
moveInterval = 0;
} else {
moveInterval = setInterval(moveIt, 50);
}
});
【问题讨论】:
-
喜欢这个? jsfiddle.net/mvbs0uu3
-
你应该把它作为答案,它看起来是正确的。
-
@jkris:将其添加为答案并不适合 SO 的使命,即“让互联网变得更美好”。这个问题太具体了,除了已经得到她的解决方案的 OP 之外,几乎不可能帮助任何人。此外,JoshCrozier 显然不需要代表。通过将解决方案作为评论提供,Josh 允许 Lily 删除问题,同时也给了她答案,所以 SO 不会再收到一个无用的问题。
-
@AndreiGheorghiu 感谢您的洞察力!只是想知道,高度具体的问题在哪里适合?
-
@jkris 这是一个灰色地带。从黑色开始:“嘿,请一位专业的开发人员为你做这件事!” 到更白:“用更通用的套装修饰您的非常具体的问题,并在其前面加上
"How to..."并且您正面临一个完全合法、有时广受好评(并且投票赞成)的问题。这一切都归结为能够为您的问题提供完美的minimal reproducible example。
标签: javascript jquery html css