2014-12-28 143 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的窗口對象(或全局對象)。否則看起來不錯。

相關問題