使用javascript滑动div [英] slide a div using javascript
本文介绍了使用javascript滑动div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想写一个javascript代码,它会在特定的方向,距离和某个给定的时间内滑动div。我写了这个小脚本。但根本不起作用。相反,浏览器变慢了。没有看到位置变化。
有人能告诉我如何实现结果吗?我知道有很多现成的库可以轻松完成。但我只是想尝试一下。
I wanted to write a javascript code that will slide a div in specific direction, distance and in some given time. I wrote this small script. but doesn't work at all. Instead browser gets slow. No change in position is visible. Can someone tell me how to achieve the result ? I know there are many ready made libraries that can do this easily. But I just wanted to give it a try.
<script type="text/javascript" language="javascript">
var element = '';
var slidePerMS = '';
function slideIt(ele, direction, distance, slideDuration){
element = ele;
var i=0;
slidePerMS = distance / (slideDuration*1000);
for(i=0; i<3000; i++){
setTimeout("changePosition()",1);
}
}
function changePosition(){
var currElement = document.getElementById(element);
currElement.style.left = "'"+slidePerMS+"px'";
}
</script>
推荐答案
SOO很多东西都错了,甚至不好笑...让我们看看...
SOO many things wrong with that code it's not even funny... Let's see...
- 您正在尝试渲染1000 FPS动画。这对于浏览器来说根本不可能。
- 您将字符串作为参数传递给
setTimeout
,这与<$ c一样邪恶$ c> eval 。 - 您设置
slidePerMS
一次,但从未更改过,导致div一遍又一遍地移动到完全相同的位置。 - 你正在设置带有额外引号的样式 - 你把引号放在CSS文件中吗?
- You are trying to render a 1,000 FPS animation. This is simply impossible for a browser.
- You are passing a string as parameter to
setTimeout
, which is as evil aseval
. - You set
slidePerMS
once but never change it after, resulting in the div being moved to the exact same spot over and over. - You are setting the style with extra quotes inside - do you put quotes in a CSS file?
这只是名字而已。请尝试这样做:
That's to name but a few. Try this instead:
<script type="text/javascript" language="javascript">
function slideIt(elem, direction, distance, slideDuration){
var elmt = document.getElementById(elem),
i=0, step = distance / (slideDuration*20),
stepper = setInterval(function() {
i = Math.min(distance,i+step);
elmt.style.left = i+'px';
if( i == distance) clearInterval(stepper);
},50);
}
</script>
这篇关于使用javascript滑动div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文