Javascript 从div访问js中的变量
我正在玩一个网站,其中8个三角形组成一个八角形,当用户在每个三角形上移动鼠标时,它会从三角形中心移动20px。目前我的JS如下所示:Javascript 从div访问js中的变量,javascript,jquery,html,jquery-animate,Javascript,Jquery,Html,Jquery Animate,我正在玩一个网站,其中8个三角形组成一个八角形,当用户在每个三角形上移动鼠标时,它会从三角形中心移动20px。目前我的JS如下所示: //pushes out the top triangle $('#top').hover( if($(this).css('moving'){ function(){ $(this).animate({top:"-=20px"}, 'slow'); }, function(){
//pushes out the top triangle
$('#top').hover(
if($(this).css('moving'){
function(){
$(this).animate({top:"-=20px"}, 'slow');
},
function(){
$(this).animate({top:"+=20px"}, 'slow');
});
}
但是我不想为每个三角形输入-20px。我实际上在想,如果每个div都存储了它需要移动的方向,那么代码可能如下所示:
$(document).ready(function(){
//pushes out the triangle the user is hovering over
$(this).hover(
function(){
$(this).animate({top: this.up}, speed);
$(this).animate({right: this.right}, speed);
},
function(){
$(this).animate({top: this.down}, speed);
$(this).animate({right: this.left}, speed);
}
);}
每个div都有向上、向下、向左和向右的变量。例如,顶部三角形的值为:
top.up= "-=20px"
top.down= "+=20px"
top.left= "+=0px"
top.right= "+=0px"
编辑:
进行以下建议的更改后,这是我的代码:
$(document).ready(function(){
// if(stationary){
// stationary=false;
$("div").hover(
function(){
$(this).animate({top: this.data('up') }, "slow");
$(this).animate({right: this.data('right') }, speed);
}
),
function(){
$(this).animate({top: this.data('down') }, speed);
$(this).animate({right: this.data('left') }, speed);
// stationary=true;
}
);
}
这不会移动div的。此外,我还添加了一个var静止变量,以便只有在当前没有div移动的情况下,div才能移动。嗯
您可以使用数据
属性:
用户可以这样使用它:
//pushes out the top triangle
$('#top').hover(
if($(this).css('moving'){
function(){
$(this).animate({top:"-=20px"}, 'slow');
},
function(){
$(this).animate({top:"+=20px"}, 'slow');
});
}
.animate({top:this.data('top-up')},速度)
你能发布一个提琴让我们看到问题吗?发布几乎相同的答案30秒后,这似乎是没有更多信息的最合理的解决方案。没错,更多信息会有所帮助;)我刚刚尝试了这个,但它不起作用,我的代码在主Post中。你能创建一个jsfiddle.com吗?