您的位置:首页技术文章
文章详情页

请问怎么点击背景,蓝色变红色,红色变蓝色呢?我代码哪里出错了吗?求助,谢谢

浏览:39日期: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出另一个