登录  /  注册
请问怎么点击背景,蓝色变红色,红色变蓝色呢?我代码哪里出错了吗?求助,谢谢
思如磐石
思如磐石 2017-12-13 17:20:50
[JavaScript讨论组]


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

QQ图片20171213171840.jpg


<!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>



思如磐石
思如磐石

全部回复(5)
***huihui
#test1 {

width:300px;

height:300px;


  • 回复 &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;style&gt; #test1 { width:300px; height:300px; background-color:blue; } &lt;/style&gt; &lt;body&gt; &lt;div id=&quot;test1&quot;&gt;&lt;/div&gt; &lt;/body&gt; &lt;script&gt; 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==&quot;rgb(0, 0, 255)&quot;){ a.style.backgroundColor=&quot;red&quot;; } else if(finalStyle.backgroundColor==&quot;rgb(255, 0, 0)&quot;){ a.style.backgroundColor=&quot;blue&quot;; } } 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(&quot;test1&quot;); addEvent(element,&quot;click&quot;,test1); } &lt;/script&gt; &lt;/html&gt;
    ***huihui 作者 2018-01-18 14:31:01
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号