4
var element = document.getElementById('text');
document.getElementById("wedding").onclick = function(){
  element.style.position = "absolute";
  element.style.left = '-450px';
  element.style.top = '-260px';
  element.style.zoom = 0.8;
  element.style.MozTransform = 'scale(0.8)';
  element.style.WebkitTransform = 'scale(0.8)';
}

我需要将上面的代码用于两个按钮。所以我像下面这样更改此代码,但它不起作用。我怎样才能做到这一点。

var element = document.getElementById('text');
document.getElementById("wedding divorce").onclick = function(){
   element.style.position = "absolute";
   element.style.left = '-450px';
   element.style.top = '-260px';
   element.style.zoom = 0.8;
   element.style.MozTransform = 'scale(0.8)';
   element.style.WebkitTransform = 'scale(0.8)';
}
4

2 回答 2

5

如果您需要为不同的元素运行相同的函数,请调用函数名称而不是函数实现本身:

document.getElementById("wedding").onclick = lalala;

document.getElementById("divorce").onclick = lalala;

//inside you can use `this` ( notice we didnt pass [this] , it is done automatically)

function lalala()
{
     this.style.position = "absolute";
     this.style.left = '-450px';
     this.style.top = '-260px';
     this.style.zoom = 0.8;
     this.style.MozTransform = 'scale(0.8)';
     this.style.WebkitTransform = 'scale(0.8)';

}

OP澄清后

var e=document.getElementById("text") 

document.getElementById("wedding").onclick =function (){ lalala(e) };

document.getElementById("divorce").onclick =function (){ lalala(e) };




function lalala(elm)
{
     elm.style.position = "absolute";
     elm.style.left = '-450px';
     elm.style.top = '-260px';
     elm.style.zoom = 0.8;
     elm.style.MozTransform = 'scale(0.8)';
     elm.style.WebkitTransform = 'scale(0.8)';

}
于 2013-08-03T08:06:24.077 回答
1
document.getElementById("btn1").onclick = apply_style();

function apply_style(){
document.getElementById("my_div").className="my_css_class";
}

In your css:

.my_css_class{
     position = "absolute";
     left = '-450px';
     top = '-260px';
     transform: scale(0.8);
     -ms-transform: scale(0.8); /* IE 9 */
     -webkit-transform: scale(0.8); /* Safari and Chrome */
}
于 2013-08-03T08:30:44.170 回答