2016-01-15 87 views
3

我對JavaScript很新穎,想要編寫html網站的標題。 JS:當窗口寬度小於1215px - >左側部分寬度爲100%時;右側部分的標題爲0JS - 無法讀取屬性'setAttribute'爲空

我總是得到「無法讀取屬性'setAttribute'爲null」錯誤!

請幫忙! 代碼:

if (window.innerWidth < 1215) { 
 
    document.getElementById("#headerLeft").setAttribute("style", "width:100%"); 
 
    document.getElementById("#headerRight").setAttribute("style", "width:0%"); 
 
} else { 
 
    document.getElementById("#headerLeft").setAttribute("style", "width:50%"); 
 
    document.getElementById("#headerRight").setAttribute("style", "width:50%"); 
 
}
body { 
 
    margin:0; 
 
} 
 

 
header{ 
 
    height:100px; 
 
    width:100%; 
 
} 
 

 
#headerLeft { 
 
    background-color:#FF7043; 
 
    height:100px; 
 
    float:left; 
 
} 
 

 
#headerRight { 
 
    background-color:#FFFFFF; 
 
    height:100px; 
 
    float:right; 
 
} 
 

 
.headerTitle { 
 
    font-family:'Roboto', sans-serif; 
 
    margin:15px; 
 
    font-size:70px; 
 
} 
 

 
#headerRight .headerTitle { 
 
    text-align:left; 
 
    color:#FF7043; 
 
    font-weight:300; 
 
} 
 

 
#headerLeft .headerTitle { 
 
    text-align:center; 
 
    color:#FFFFFF; 
 
    font-weight:900; 
 
}
<!doctype html> 
 
<html> 
 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title>example</title> 
 
    
 
    <!-- css --> 
 
    <link type="text/css" rel="stylesheet" href="style.css"> 
 
    
 
    <!-- fonts --> 
 
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,500,700,900,100,300' rel='stylesheet' type='text/css'> 
 
    
 
    <!-- javascripts --> 
 
    <script language="javascript" type="text/javascript" src="script.js"></script> 
 
    
 
</head> 
 
<body> 
 
    <header> 
 
     <div id="headerLeft"> 
 
      <p class="headerTitle">example</p> 
 
     </div> 
 
     
 
     <div id="headerRight"> 
 
      <p class="headerTitle">example</p> 
 
     </div> 
 
    </header> 
 
    
 
    <nav> 
 
    </nav> 
 
    
 
    <main> 
 
    </main> 
 
    
 
    <footer> 
 
    </footer> 
 
</body> 
 
</html>

+2

不回答你的問題,但你可能想看看[媒體查詢(https://developer.mozilla.org/en- US/docs/Web/CSS/Media_Queries/Using_media_queries) –

回答

5

這是因爲所有的呼叫document.getElementById都沒有找到任何東西,因爲不存在具有這些ID的任何元素。看起來像jQuery的習慣,從你的ID中刪除#

+0

看起來它也運行得太快...... –

+0

是的,腳本應該包含在頁面的ad _bottom_中,而不是在頭部。或者它應該被封裝在window.load事件的eventListener中。 – juandemarco

1

首先通過Id選擇沒有'#'。 二是設定風格,這樣的方式:

document.getElementById('').style.width = "20%";