按ID问题获取元素?

时间:2012-01-23 00:32:38

标签: javascript image onclick fadein getelementbyid

我正在尝试使用带有onclick命令的图像来淡入框。但我很遗憾为什么它不起作用。

任何帮助将不胜感激!这是代码:

<style>
  article, aside, figure, footer, header, hgroup,
  menu, nav, section { display: block; }
   #box { background:#999; width:500px; height:500px;opacity:0; }
</style>
</head>

  <div id="box"><id="box"></div>
  <div id="img"><img src="img.png" width="37" height="28" id="img"></div>


<script>
    var elem = document.getElementById("img","box");
    // attach event handler
   "img".onclick = function(){
      fadeIn( "img", 400 );
      this.onclick = null;
    };

    function setOpacity( obj, value ) {
      if ( obj ) {
        obj.style.opacity = value / 100;
        obj.style.filter  = 'alpha(opacity=' + value + ')';
        obj.style.zoom    = 1;
      }
    }

    // makes an element to fade in
    function fadeIn( dom, interval, delay ) {

          interval  = interval || 1000;
          delay     = delay    || 10;

      var opacity   = 0,
          start     = Number(new Date()),
          op_per_ms = 100 / interval;

      if ( typeof dom === "string" ) {
        dom = document.getElementById( dom );
      }

      function step() {

        var now     = Number(new Date()),
            elapsed = now - start;
            opacity = elapsed * op_per_ms;

        setOpacity( dom, opacity );

        if ( elapsed < interval )
          setTimeout( step, delay );
        else
          setOpacity( dom, 100 );
      }

      setTimeout( step, delay );
    }

</script>

2 个答案:

答案 0 :(得分:2)

getElementById没有多于1个参数

var elem = document.getElementById("img");
var elem2 = document.getElementById("box");

您的IE事件处理程序也是从String调用方法。

elem.onclick = function(){
  fadeIn(this, 400 );
  return false;
};

答案 1 :(得分:0)

我认为你在第一段代码中犯了两个错误:

<script>
    var elem = document.getElementById("img","box");
    // attach event handler
   "img".onclick = function(){
      fadeIn( "img", 400 );
      this.onclick = null;
    };

首先:

var elem = document.getElementById("img","box");

是错误的,因为函数getElementById只接受一个参数。如果你想获得两个元素,你应该使用两个不同的调用:

var img = document.getElementById("img");
var box = document.getElementById("box");

其次是什么?

"img".onclick = function(){

我认为你的意思是:

elem.onclick = function(){

第一次更正的内容变为:

    img.onclick = function(){
      fadeIn( "img", 400 );
      this.onclick = null;
    };

    box.onclick = function(){
      fadeIn( "box", 400 );
      this.onclick = null;
    };