1. 程式人生 > 其它 >JavaScript操作頁面元素

JavaScript操作頁面元素

(1)修改元素內容
// innerText,不識別htm1標籤,非標準,去除空格和換行
// innerHTML,識別html標籤,W3C標準,保留空格和換行的
// 都可讀寫,可以獲取元素裡的內容
var text = document.querySelector('span');
var p = document.querySelector('p');
text.innerText = 'none'; //頁面載入時修改元素內容
p.innerHTML = '今天週二';//常用

 (2)修改元素屬性
// 元素.屬性
var ldh = document.getElementById('ldh');
var zxy = document.getElementById('zxy');
var img = document.querySelector(' img ');
zxy.onclick = function() {
    img.src = 'images/zxy.jpg '; //示範
    img.title = 'zxy';
}
ldh.onclick = function() {
    img.src = ' images/1dh.jpg'; //示範
    img.title = 'ldh';
}

(3)修改樣式屬性
var div = document.querySelector('div');
div.onclick = function() {
    this.style.backgroundColor = 'purple'; //元素.style.屬性
    this.style.width = '250px';
    this.className = "change"; // 元素.className,,,相當於給元素添加了change類,會覆蓋掉原有的類
    this.className = " first change"; // 保留原有的類first,
}