赫塔缪勒_FreshFish
2019-08-22 11:06
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>changeClass</title> <style> .one { font-size:20px; color:#A0A; background-color:#FA0; } .two { font-size:50px; color:#000; background-color:#00F; } input { font-size:50px; } </style> </head> <body> <form> <input type="button" value="change_class_button" onclick="onChangeClass()"/> </form> <p id="testID" class="one">Javascript abc 汉字</p> <script> var some=document.getElementById("testID"); document.write("元素p的class值为"+some.className); function onChangeClass() { if(some.className == "one") { some.className="two"; } else { some.className="one"; } } </script> </body> </html>
连续点击按钮,p内文字style会切换,但最后显示文字时,one和two不会切换,为什么?怎么写才对?
document.write("元素p的class值为"+some.className);
只是打印了第一遍,click的时候改变的只是style.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>changeClass</title>
<style>
.one
{
font-size:20px;
color:#A0A;
background-color:#FA0;
}
.two
{
font-size:50px;
color:#000;
background-color:#00F;
}
input
{
font-size:50px;
}
</style>
</head>
<body>
<form>
<input type="button" value="change_class_button" onclick="onChangeClass()"/>
</form>
<p id="testID" class="one">Javascript abc 汉字</p>
<p>元素p的class值为<span id=ha1></span></p>
<script>
var some=document.getElementById("testID");
var ha1=document.getElementById("ha1")
function onChangeClass()
{
if(some.className == "one")
{
some.className="two";
ha1.innerHTML=some.className;
}
else
{
some.className="one";
ha1.innerHTML=some.className;
}
}
</script>
</body>
</html>
//这样更为符合!!!!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>changeClass</title>
<style>
.one
{
font-size:20px;
color:#A0A;
background-color:#FA0;
}
.two
{
font-size:50px;
color:#000;
background-color:#00F;
}
input
{
font-size:50px;
}
</style>
</head>
<body>
<form>
<input type="button" value="change_class_button" onclick="onChangeClass()"/>
</form>
<p id="testID" class="one">Javascript abc 汉字</p>
<p id="ha1">元素p的class值为</p>
<script>
var some=document.getElementById("testID");
var ha2=document.getElementById("ha1")
function onChangeClass()
{
if(some.className == "one")
{
some.className="two";
ha2.innerHTML="元素p的class值为two"
}
else
{
some.className="one";
ha2.innerHTML="元素p的class值为one"
}
}
</script>
</body>
</html>
!!!!!!!!!!!!!!可以改成这样
JavaScript入门篇
739817 学习 · 9566 问题
相似问题