2014-01-05 18 views
2

正如標題所說,我正在尋找一種有效的方式來移動一個按鈕,當鼠標移動到它上面時(只是爲了一個我正在處理的小項目)。我決定使用jQuery,但是我遇到了以下代碼的麻煩。因爲它在語法上是正確的(我相信),沒有錯誤被拋出,但按鈕沒有按照預期移動。任何幫助將不勝感激,謝謝。如何使用jQuery移動<input>元素?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <script src = "jquery.js"></script> 
    <title>Click The Button!</title> 
</head> 

<body> 
    <input type="button" value="Try and Click Me!"> 
<script> 
$("input").mouseenter(function(){ 
    $(this).style.position = "absolute"; 
    $(this).style.left = Math.floor(Math.random()*600)+"px"; 
    $(this).style.top = Math.floor(Math.random()*400)+"px"; 
}); 
</script> 
</body> 

</html> 

強制性的編輯,以感謝所有回覆他們正確回覆的人!非常感激。

回答

3

處理jQuery對象時,如$(this)使用css函數來調整CSS屬性。在訪問本地DOM元素的屬性時使用element.style.left等,而不是使用jQuery選擇的元素。

$("input").mouseenter(function(){ 
    $(this).css("position","absolute"); 
    $(this).css("left", Math.floor(Math.random()*600)+"px"); 
    $(this).css("top",Math.floor(Math.random()*400)+"px"); 
}); 

JS小提琴:http://jsfiddle.net/5LWAk/

+0

一兩件事在這裏補充。 'css'也接受一個對象。所以,你可以保存一些函數調用。如果您同時指定所有屬性,它也會更乾淨。 – Jashwant

+0

非常感謝Kevin和Jashwant對這個小小的見解。編輯:如果我有足夠的聲望點,會'upvote'。 :) – 1mmortal

+0

@ 1mmortal很高興能幫到你! –

0
$("input").mouseenter(function(){ 
      $(this).css({left:Math.floor(Math.random()*600) 
      ,top:Math.floor(Math.random()*600) 
      ,position:"absolute"}); 

    }); 

Check on Fiddle

1

這給一個鏡頭:

$("input").mouseenter(function() { 
    $(this).css({ 
     "position":"absolute", 
     "left": Math.floor(Math.random() * 600) + "px", 
     "top": Math.floor(Math.random() * 400) + "px" 
    }); 
}); 

這裏是一個fiddle

0

更改您輸入要添加ID:

<input id="mybutton" type="button" value="Try and Click Me!"> 

然後你就可以訪問按鈕

<script> 
$("#mybutton").mouseenter(function(){ 
$(this).css({ 
    position: "absolute", 
    left: Math.floor(Math.random()*600)+"px", 
    top: Math.floor(Math.random()*400)+"px" 
}); 
}); 
</script>