[英]Javascript function - style change not working
I created a 2 simple functions but function 2 doesn't work, I tried to change it to style.font-weight = "bold";
我创建了2个简单的函数,但函数2不起作用,我尝试将其更改为style.font-weight = "bold";
but then all crashes, what to do? 但是所有崩溃都该怎么办?
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> </head> <body> <div id="text" style="font-weight: normal">hello world!</div> <input id="remember" type="checkbox" onclick="validate()">Caps</input> <br> <input id="remember2" type="checkbox" onclick="validate2()">Bold</input> <script> function validate() { if (document.getElementById('remember').checked) { document.getElementById("text").innerHTML = "HELLO WORLD!"; } else { document.getElementById("text").innerHTML = "hello world!"; } } function validate2() { if (document.getElementById('remember2').checked) { document.getElementById("text").style = "bold"; } else { document.getElementById("text").style = "normal"; } } </script> </body> </html>
Is that a chrome problem or something? 那是镀铬的问题吗?
You aren't specifying the css property to be changed: 您没有指定要更改的css属性:
document.getElementById("text").style.fontWeight = "bold";
Javascript uses camelCase
instead of a dash( camel-case
), as CSS does, so style.font-weight
is invalid. 与CSS一样,Javascript使用camelCase
而不是dash( camel-case
),因此style.font-weight
无效。
Also note that your <input>
syntax is incorrect, inputs are self-closing tags and their text is set with the value
attribute(in this case the input is a checkbox, and can't have a value): 还要注意,您的<input>
语法不正确,输入是自动关闭的标记,并且其文本使用value
属性设置(在这种情况下,输入是复选框,并且不能有值):
<input id="remember2" type="checkbox" onclick="validate2()">Bold
use this may help you 用这个可能对你有帮助
function validate2() {
if (document.getElementById('remember2').checked) {
document.getElementById("text").style.fontWeight = "bold";
}
else {
document.getElementById("text").style.fontWeight = "normal";
}
}
function validate2() {
if (document.getElementById('remember2').checked) {
document.getElementById("text").style.fontWeight = "bold";
}
else {
document.getElementById("text").style.fontWeight = "normal";
}
}
You were not setting the correct style property. 您没有设置正确的样式属性。
var text = document.getElementById("text"); function validate(checkbox) { if (checkbox.checked) { text.innerHTML = text.innerHTML.toUpperCase(); } else { text.innerHTML = text.innerHTML.toLowerCase() } } function validate2(checkbox) { if (checkbox.checked) { text.style.fontWeight = "bold"; } else { text.style.fontWeight = "normal"; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> </head> <body> <div id="text" style="font-weight: normal">hello world!</div> <input id="remember" type="checkbox" onclick="validate(this)">Caps</input> <br> <input id="remember2" type="checkbox" onclick="validate2(this)">Bold</input> <script> </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.