2011-11-03 41 views
0

那么,什么问题?我有一个“位置:绝对”属性的div。现在 - 我想知道 - 每当鼠标移动时,我可以使用jQuery(或简单的JavaScript)移动这个div吗?这只是一个不断增加的动作,只能在X轴上进行。因此 - 想象一下浏览器窗口的左侧和右侧。当 - 例如 - 鼠标光标位于左半部分时 - 此div始终缓慢向右移动;而且当光标越来越靠近左边时 - div的速度会增加一点。我正在尝试在Three.js引擎上学习WebGL。让我告诉你一个例子:jQuery和WebGL - 在鼠标移动时移动div

看看这里 - http://hadyk.pl/webgl/(可能不工作在IE)

看星星是移动的样子,当你移动光标 - 我要实现与相同背景div。

感谢

编辑:好吧,我得到它的工作。看升级的链接。代码:

脚本:

$('#background').css({backgroundPosition: "0px bottom"})

function moveRight() { 
       $('#background').stop().animate({right: "1500px"}, 
       {duration:80000}); 
} 
function moveLeft() { 
       $('#background').stop().animate({right: "-1500px"}, 
       {duration:80000}); 
} 
function onStop() { 
       $('#background').stop(); 
} 

HTML:

<div id="background"></div> 
<div id="left" onMouseOver="moveLeft()" onMouseOut="onStop()"></div> 
<div id="right" onMouseOver="moveRight()" onMouseOut="onStop()"></div> 

CSS:

#background { 
      background: #000 url(images/moon.png) no-repeat; 
      position:absolute; 
      bottom:0; 
      right:0; 
      width:411px; 
      height:404px; 
      z-index:-2; 
} 
#left { 
      position:absolute; 
      left:0; 
      bottom:0; 
      width:30%; 
      height:100%; 
      z-index:99 
} 
#right { 
      position:absolute; 
      right:0; 
      bottom:0; 
      width:30%; 
      height:100%; 
      z-index:99 
} 

回答

0

我这里得到一个错误:

function moveBackground() { 
    $('#background').css({'right':(parseInt($('#background').css('right')) + (e.pageX*0.001))+'px'}); 
window.setTimeout(moveBackground(), 50); 
} 

你在函数参数忘了e

function moveBackground(e) { 
    $('#background').css({'right':(parseInt($('#background').css('right')) + (e.pageX*0.001))+'px'}); 
window.setTimeout(moveBackground(), 50); 
} 
+0

好吧,我纠正它 - 做类似的东西(但它不工作):$(“画布”)鼠标移动(函数moveBackground(e){ \t如果(例如X>(window.innerWidth/2)) ').css('right'))+(e.pageX * 0.0008))+'px'}); \t \t} \t \t如果(e.pageX <(window.innerWidth/2)){ \t \t $( '#背景')。CSS({ '右' :(parseInt函数($( '#背景') .css('right')) - (e.pageX * 0.0008))+'px'}); \t \t} \t}); – Irminsul

+0

在你的功能减速中删除'moveBackground'。它应该是'mousemove(function(e){'。另外,你的第二个'if'语句真的是多余的。用'else'子句代替 – Blender

+0

好吧,我用不同的方法来发现插件 - http://plugins.jquery.com/project/backgroundPosition-Effect。请再看看我的第一篇文章中的链接,现在它效果更好 - 但仍然有两个问题:1.为什么它在Firefox中速度太慢, Chrome?2.我不能让它在两边工作 - 它只向左移动,我错过了什么?条件是否错误 - if(mouseX>(window.innerWidth/2)){'? – Irminsul