您的位置:首頁技術文章
文章詳情頁

請問怎么點擊背景,藍色變紅色,紅色變藍色呢?我代碼哪里出錯了嗎?求助,謝謝

瀏覽:83日期:2024-06-06 08:25:37

問題描述

請問怎么點擊背景,藍色變紅色,紅色變藍色呢?我代碼哪里出錯了嗎?求助,謝謝

請問怎么點擊背景,藍色變紅色,紅色變藍色呢?我代碼哪里出錯了嗎?求助,謝謝

<!DOCTYPE html>

<html>

<head>

</head>

<style>

#test1 {

width:300px;

height:300px;

background:blue;

}

#test2 {

width:300px;

height:300px;

background:red;

}

</style>

<body>

<div id="test1" onclick="te()"></div>

</body>

<script>

function te(){

var a = document.getElementById('test1');

if(a.id == 'test1'){

a.id = 'test2';

}else

a.id = 'test1';

}

</script>

</html>

問題解答

回答1:

<!DOCTYPE html><html><head></head><style>#test1 {width:300px;height:300px;background-color:blue;}</style><body><div id="test1"></div></body><script> function test1() {var a = document.getElementById('test1');var finalStyle = a.currentStyle ? a.currentStyle : document.defaultView.getComputedStyle(a, null);/*利用判斷是否支持currentStyle(是否為ie)13 來通過不同方法獲取style*/if(finalStyle.backgroundColor=="rgb(0, 0, 255)"){a.style.backgroundColor="red"; }else if(finalStyle.backgroundColor=="rgb(255, 0, 0)"){a.style.backgroundColor="blue"; } } function addEvent(obj,type,handle){ try{ // Chrome、FireFox、Opera、Safari、IE9.0及其以上版本obj.addEventListener(type,handle,false); }catch(e){try{ // IE8.0及其以下版本 obj.attachEvent('on' + type,handle);}catch(e){ // 早期瀏覽器 obj['on' + type] = handle;} }} window.onload = function(){var element = document.getElementById("test1");addEvent(element,"click",test1); }</script></html>

回答2:

#test1 {width:300px;height:300px;

回答3:

你可以用addinventlisner(),監聽點擊事件,初始化給紅色,點擊第一次改變成藍色,再點擊變紅色

準備一個class{background-color:#f00},當你點擊的時候給它添加一個類名,再點擊的時候讓它移除那個類名

你可以用移入移出事件

回答4:

第二次執行的時候a是undefined。把var a = document.getElementById('test1');放在函數外面就可以了

回答5:

不應該是只改個id,你匹配成功就show出另一個

国产综合久久一区二区三区