2013-02-10 54 views
1

我想實現可訪問性工具,我設法改變一個段落的字體大小,一旦按鈕被點擊,但我試圖改變代碼,以便它會在所有段落工作,這是行不通的使用按鈕來改變整個網站使用javascript的字體大小

<script> 

function myFunction() 

{ 
var p =document.getElementsByTagName('p'); // Find the element 
p.style.fontSize="1.5em";   // Change the style 
} 
</script> 

<button type="button" style="background: #ccc url(images/small.jpg); padding: 0.3em 1em" onclick="myFunction()"></button> 

這是怎麼只是一個段落前的工作,但我試圖不止一個:

<script> 
function myFunction() 
{ 
x=document.getElementById("demo") // Find the element 
x.style.fontSize="3.0em";   // Change the style 
} 
</script> 
+0

請通過'src'屬性與CSS添加圖片。當你使用'src'時'alt'屬性有效。否則,這個「按鈕」不可訪問。 – 2013-02-10 19:15:55

回答

3

getElementsByTagName返回NodeList,這是像一個數組,所以你h通過他們AVE循環和樣式應用到每一個元素:

function myFunction() { 
    var arr = document.getElementsByTagName('p'); 
    for (var i = 0; i < arr.length; i++) { 
     arr[i].style.fontSize = "1.5em"; 
    } 
} 
2

你的第一個代碼塊的問題是,返回的getElementsByTagName元素的節點列表(你可以假裝是一個數組)。所以你需要這樣做:

var p =document.getElementsByTagName('p'); // Find the element 
for(var i=0; i<p.length; i++) { 
    p[i].style.fontSize="1.5em";   // Change the style 
    } 

但是,更好的方法是定義一些css類爲你做這個工作。

<style> 
body { /*normal size*/ 
    font-size: 1em; 
} 

body.largeFont { 
    font-size: 1.5em; 
} 
</style> 

<script> 
function largeFont() { 
    document.body.className="largeFont"; 
} 
</script> 
+1

'getElementsByTagName()'返回一個[NodeList](https://developer.mozilla.org/en-US/docs/DOM/NodeList),它是_not_一個Array:(。 – Teemu 2013-02-10 15:54:05

+0

當然,謝謝Teemu! – jlarson 2013-02-10 22:32:03