2014-03-29 37 views
4

我有一個顯示小紅球和JAVASCRIPT函數的CSS ID。我想在JavaScript函數中將CSS id作爲參數傳遞。我看過很多教程,但無法弄清楚。下面是代碼:將CSS ID作爲JavaScript函數中的參數傳入

CSS代碼

#projectile{ 
    position: absolute; 
    background-color: #ff0000; 
    left:176px; 
    top: 486px; 
    width:10px; 
    height:10px; 
    border-radius: 8px; 
    z-index: 9; 
} 

JavaScript代碼

function gofish(projectile_id){ 
var projectile = getElementbyId(projectile_id); 
start_x = projectile.offset().left; 
start_y = projectile.offset().top; 

function init() 
{ setTimeout("gofish('projectile')", 500); } 
+0

你有一個'getElementbyId'函數,或者你實際上是否指'document.getElementbyId' – adeneo

+0

它看起來像你使用'offset()'f中的jQuery聯合? – adeneo

+0

打開瀏覽器控制檯,您會發現查看錯誤消息很有用。 – jdigital

回答

2

讓我們假設你正在使用jQuery和你想要一個jQuery對象使用offset()方法,這樣的方法並不對於普通DOM節點存在

function gofish(projectile_id){ 
    var projectile = $('#' + projectile_id); 
    var start_x = projectile.offset().left; 
    var start_y = projectile.offset().top; 
} 

function init() { 
    setTimeout(function() { 
     gofish('projectile'); 
    }, 500); 
} 
+0

的回答。它應該是'projectile = $('#'+ projectile_id);'而不是'var projectile = $('#'+ projectile_id);'。 Tnx,它幫助了很多! :) –

+0

這將使全局變量,你通常應該避免,但如果它的工作原理,它的作品。樂於幫助! – adeneo

2

在Java中有一些錯誤腳本。

  • getElementById應該有一個大寫'b',並且應該針對文檔調用。
  • 我認爲你正在尋找的偏移屬性是element.offsetLeft和element.offsetTop。
  • 您可以直接在setTimeout上定義一個匿名函數來調用init(),完全按照adeneo的建議。
  • 您仍然需要在某處調用init()以使其運行。

這裏被更新的JavaScript代碼:

function gofish(projectile_id) { 
    var projectile = document.getElementById(projectile_id); 
    start_x = projectile.offsetLeft; 
    start_y = projectile.offsetTop; 
} 

function init() { 
    setTimeout(function() { 
     gofish('projectile'); 
    }, 500); 
} 

init(); 

這裏是在動作的代碼,到目前爲止:http://jsfiddle.net/JuvDX/

0

這可能會幫助你一點...

<!DOCTYPE html> 
<html> 
<head> 

<script> 
function myFunction(element) 
{ 
alert(document.getElementById(element.id).value); 
} 
</script> 
<style> 
#para1 
{ 
text-align:center; 
color:red; 
} 
</style> 
</head> 

<body> 
<p id="para1" onclick="myFunction(this)" name="paragraph" >Hello World!</p> 
</body> 
</html> 
相關問題