Ive been working on creating a swinging effect in javascript so that a number of objects, when the mouse moves over them will however and then slowly keep hovering until they stop.
我一直致力于在Java脚本中创建一种摆动效果,这样当鼠标移动到一些对象上时,它们会慢慢地保持悬停,直到它们停止。
I have got this working in JSFiddle: http://jsfiddle.net/z3s7v/58/
我已经在JSFdle中实现了这一点:http://jsfiddle.net/z3s7v/58/
Here is the Js that I have:
以下是我的Js:
(function(){
var box=document.getElementById('box');box2=document.getElementById('box2');box3=document.getElementById('box3');
swing(box);swing(box2);swing(box3);
function swing(box) {
var ang = 20,
dAng = 10,
ddAng = .5,
dir = 1;
function setAng(ang){
box.style.WebkitTransform = 'rotate('+ang+'deg)';
box.style.MozTransform = 'rotate('+ang+'deg)';
dir = -dir;
if (dAng > 1)
dAng -= ddAng;
if (Math.abs(ang) > 0)
setTimeout(setAng, 1000, dir * (Math.abs(ang)-dAng));
};
box.onmouseover = function(){
box.style.WebkitTransform = 'rotate(-20deg)';
box.style.MozTransform = 'rotate(-20deg)';
setTimeout(function(){
setAng(ang)
}, 1000);
}
};
}())
Also as a second question if anyone can answer this, the more boxes I add the jerkier and more rigid the swinging seems to be.
同样作为第二个问题,如果有人能回答这个问题,我加的盒子越多,摇摆看起来就越笨拙和僵硬。
Appreciate all the help folks.
感谢大家的帮助。
更多回答
Why are you not using jQuery if you have it included and tagged?
如果包含并标记了jQuery,为什么不使用它呢?
Please choose the jQuery Lib from the left side menu in your fiddle. It works!!!
请从您的小提琴左侧菜单中选择jQuery库。它成功了!
I have already said that it works on JSFiddle it. Doesnt work in a web page
我已经说过,它可以在JSFdle it上运行。在网页中不起作用
优秀答案推荐
Wrap code in
将代码包装在
window.onload = function(){
// your code
};
The reason might be because you are trying to set the variable before the elements are loaded so the variable gets set to null. the way to fix this would be to go into your html file and replace this:
原因可能是您试图在加载元素之前设置变量,以便将变量设置为空。解决此问题的方法是进入您的html文件并替换以下内容:
<script src="path/to/file.js" ></script>
with this
有了这个
<script defer src="path/to/file.js" ></script>
so by adding the defer
attribute, you tell the browser to execute you javasctipt after the page is loaded.
因此,通过添加defer属性,您可以告诉浏览器在页面加载后执行您的javasctipt。
I know this is a little late but I found the solution so here you go.
我知道这有点晚,但我找到了解决办法,所以给你。
更多回答
我是一名优秀的程序员,十分优秀!