2014-12-28 146 views
0

我想用JS激活CSS。假设我有这个代码,并且我想在第一次点击时放大图片,然后在第二次点击后将其发送到右侧,但它不起作用。功能是否正确?如何与JS一起使用CSS

如何使用JavaScript控制元素的CSS?

<script> 
    function function(){ 
     var house = document.getElementById("house"); 
      if(this.className == "mystyle") 
       this.className = "mystyle2"; 
      else 
       this.className = "mystyle"; 
    } 
</script> 

<a href="#" style="text-decoration: none"><img src="casa1.jpg" id="house" width="200" height="150" onclick="function()"> 

我想它来激活这个CSS:

.mystyle { 
position: absolute; 
left: 50%; 
margin-left: -100px; 
} 

.mystyle2{ 
    float: right; 
} 
+4

您不能给函数名称“function”。如果您检查(您应该),您应该在浏览器控制台中看到一个错误。 – Pointy

+0

我编辑它,即时通讯有一个不同的名字。 – Angelo

+0

不是真的重复。因为我不知道如何使该功能在第二次点击时做其他事情。 – Angelo

回答

1

你的代码是好的,但你的范围是坏的。取而代之的this里面的功能,你需要使用house

function function1() { 
 
    var house = document.getElementById("house"); 
 
    if (house.className == "mystyle") 
 
    house.className = "mystyle2"; 
 
    else 
 
    house.className = "mystyle"; 
 

 
}
.mystyle { 
 
    position: absolute; 
 
    left: 50%; 
 
    margin-left: -100px; 
 
} 
 

 
.mystyle2 { 
 
    float: right; 
 
}
<img src="http://images.clipartpanda.com/cute-house-clipart-house_clipart_12.gif" id="house" width="200" height="150" onclick="function1()">

+1

谢谢。工作很好。 – Angelo

1

更换这个,与房子。在JavaScript中这个总是指向我们正在执行的函数的“所有者”,或者更确切地说,指的是函数是其方法的对象。当你在页面中定义函数function1()时,它的所有者就是页面,或者说,是JavaScript的窗口对象(或全局对象)。否则看起来不错。

相关问题