2017-06-14 48 views
1

我想用css,jquery和html为学校制作图形化演示文稿,我需要一个矩形移动屏幕。我已经做了一些研究,并且尝试过使用animate函数的几个变体,但它不能解决问题,它只能位于窗口的左侧。使用.animate移动css形状

这里是我的代码,以供参考:

var derp = 20; 
 
function scroll() { 
 
    var scrollLeft = Math.floor(Math.random() * 100); 
 
    $('#rectangle').animate({ 
 
    left: scrollLeft "px", 
 
    }, derp, function() { 
 
    scroll(); 
 
    }); 
 
} 
 

 
setInterval(100, scroll());
html, 
 
body { 
 
    width: 100%; 
 
    height: 100%; 
 
    min-height: 100%; 
 
} 
 

 
body { 
 
    background-image: url("background.jpg"); 
 
    background-repeat: no-repeat; 
 
    background-position: right top; 
 
    background-size: cover; 
 
} 
 

 
.rectangle { 
 
    width: 20px; 
 
    height: 100%; 
 
    background: black; 
 
} 
 

 
#rectangle { 
 
    left: 10px; 
 
    position: absolute; 
 
} 
 

 
img, 
 
div, 
 
p, 
 
body { 
 
    margin: 0px; 
 
    padding 0px; 
 
}
<div class="rectangle"></div> 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

+0

我想我可能有一些遗漏涉及jQuery的,但林不知道 – V3ngence91

+0

你一个语法错误,我可以看到。检查您的浏览器的开发控制台(按F12,然后单击“控制台”)以查看它所在的线路。此外,不是一个语法错误,而是一个逻辑错误,行'setInterval(100,scroll());'应该是'setInterval(scroll,100);',即函数*名称*第一(后面没有括号), *然后*毫秒的延迟。而且,从'.animate()'完成回调*中调用'scroll()'也是没有意义的,正如使用'setInterval()'一样。 – nnnnnn

回答

0

你可以只用CSS做到这一点。

div { 
 
    width: 100px; 
 
    height: 100px; 
 
    background: red; 
 
    position: relative; 
 
    animation: anim 3s forwards alternate; 
 
    animation-iteration-count: 6; 
 
} 
 

 
@keyframes anim { 
 
    from { 
 
    left: 0px; 
 
    } 
 
    to { 
 
    left: 200px 
 
    } 
 
}
<div></div>

+0

但是,OP有'Math.floor(Math.random()* 100)'这个新的位置...... – nnnnnn

+0

这就是看它是否会移动@nnnnnn – V3ngence91

+0

@ V3ngence91 - 我们可以做出有根据的猜测,但我们可以没有读懂你的思想,所以认为你包含'.random()'代码并不是不合理的,因为你实际上需要一个随机移动。如果这只是为了测试,你应该编辑你的问题以清楚地说明(也许在这一点上对代码添加注释),然后清楚地解释你实际上想要的。 – nnnnnn