2014-09-24 44 views
-2

我需要一些幫助。我寫了一個javascript來檢查URL,如果url等於example.com,那麼腳本應該改變div元素的高度和邊距。 它的作品,但它不斷重新加載站點,我不能點擊任何東西。Javascript get Element

另外我怎樣才能上課呢? getElementsByClassName不起作用。

function verschieben() { 
    if (window.location.href = "example.com") { 
     document.getElementById('bigimg').style.height = "200px"; 
     document.getElementById('searchbox').style.marginTop = "30px"; 
    } 
} 

verschieben(); 
+5

'if(window.location.href ==「example.com」)' – 2014-09-24 08:15:51

+2

in if condition it should == == instaed of = – 2014-09-24 08:16:25

+0

'getElementsByClassName'將返回一個類似於對象的數組,因此您需要循環它或獲取正確的索引。你可以創建一個小提琴或什麼的,因爲這一點代碼本身不會讓你的網站打破我的想法。 – putvande 2014-09-24 08:18:20

回答

0

如果你想獲得當前頁面的主機信息,然後window.location.host將有一個價值,href將包含完整的URL

if (window.location.host.toString() == "example.com") 
0

您的類操作的代碼應該是這樣的:

function reshapeDivs(){ 
 
    var divs = document.getElementsByClassName("someClass"); 
 
    for(i=0;i<divs.length;i++){ 
 
    divs[i].style.height = "200px"; 
 
    divs[i].style.marginTop = "30px" 
 
    } 
 
}
<div class="someClass" style="border:1px solid red">blah1</div> 
 
<div class="someClass" style="border:1px solid black">blah2</div> 
 
<button id="reshapeButton" onclick="reshapeDivs()">reshape divs</div>