javascript 点击改变div 名

这段JS 点击改变DIV名,如何实现,点击改变再点击改变,循环, 
<!DOCTYPE html>
<html>
<head>
<style>
.c1{background:red;}
.c2{ background:blue;}
</style>
</head>
<body>
<script>
function changeclass(){
  var divEle= document.getElementById('diva');
  divEle.className='c2'; 
}
</script>
<div id='diva' class='c1'>111</div>
<input type='button' onclick='changeclass()' value='改变名字'/>
</body>
</html>


ABOUTYOU
浏览 824回答 4
4回答

温温酱

不是改变名字是改变样式吧?现在代码的问题是点击触发事件后,函数中始终将className设置为c2,因此不会改变加上判断,如果当前为c2则改为c1,如果为c1则改为c2三元表达式不熟悉的话可以写成<script>&nbsp; &nbsp; &nbsp; &nbsp; function changeclass(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var divEle= document.getElementById('diva');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(divEle.className == 'c2'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; divEle.className = 'c1'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; divEle.className = 'c2'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script>

慕的地8271018

$(document).ready(function(){$("button").click(function(){$('#diva').toggleClass(function(){return 'c2'});});});

白板的微信

修改script标签<script> &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;flag&nbsp;=&nbsp;true; &nbsp;&nbsp;&nbsp;&nbsp;function&nbsp;changeclass(){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;divEle=&nbsp;document.getElementById('diva'); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(flag){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;divEle.className='c2'; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;flag&nbsp;=&nbsp;false; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}else{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;divEle.className='c1'; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;flag&nbsp;=&nbsp;true; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;} </script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript