简体   繁体   English

将CSS id作为JavaScript函数中的参数传递

[英]Pass CSS id as a parameter in JavaScript function

I've a CSS id which shows a small red ball and a JAVASCRIPT function. 我有一个CSS id,显示一个小红球和一个JAVASCRIPT函数。 I want to pass the CSS id as a parameter in the JavaScript function. 我想将CSS id作为JavaScript函数中的参数传递。 I've seen a lot of tutorials but can't figure it out. 我已经看过很多教程,但无法弄明白。 Here are the codes: 以下是代码:

CSS code CSS代码

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

JAVASCRIPT code 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); }

Lets assume you're using jQuery and that you want a jQuery object to use the offset() method as no such method exists for plain DOM nodes 让我们假设您正在使用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); 
}

You have a few mistakes in your JavaScript. 您的JavaScript中有一些错误。

  • getElementById should have a capital 'b', and should be called against document. getElementById应该有一个大写'b',应该针对document调用。
  • I think the offset properties you are look for are element.offsetLeft and element.offsetTop. 我认为你要寻找的偏移属性是element.offsetLeft和element.offsetTop。
  • You can define an anonymous function directly on setTimeout to call init(), exactly as adeneo has suggested. 你可以直接在setTimeout上定义一个匿名函数来调用init(),就像adeneo所建议的那样。
  • You will still need to call init() somewhere in order for it to run. 您仍然需要在某处调用init()才能运行它。

Here is updated JavaScript code: 这是更新的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();

And here is the code in action, so far: http://jsfiddle.net/JuvDX/ 到目前为止,这是代码在行动: http//jsfiddle.net/JuvDX/

This may help you little.. 这可能对你有所帮助..

    <!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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM