[英]The CSS rule doesn't applies any effect when JavaScript is executed
I am a newbie in web, now I'm studying JS. 我是网络新手,现在正在学习JS。 I have this simple script to be executed:
我有一个简单的脚本要执行:
<script language="javascript">
var getDate = function() {
var doc = document.getElementById("demo");
doc.innerHTML = Date();
}
</script>
And this CSS rule for the label in which the script will be shown: 这是显示脚本的标签的CSS规则:
<style type="text/css">
.cstyle {
font-family: "Comic Sans MS", cursive;
}
</style>
In my document I have a button that triggers my script 在我的文档中,有一个触发脚本的按钮
<p id="demo"><span class="cstyle">Result.</span></p>
<button type="button" onClick="getDate()">Display Data</button>
When the document is being loaded "Result" is displayed with "Comic Sans" font. 加载文档时,“结果”以“ Comic Sans”字体显示。 But when the mouse click has been happened, the date is displayed with the default font.
但是,当单击鼠标时,将以默认字体显示日期。 This behaviour is abnormal, because script execution result is needed to be displayed with "Comic Sans" font too.
此行为异常,因为脚本执行结果也需要使用“ Comic Sans”字体显示。 How can I fix this?
我怎样才能解决这个问题?
[Upd.] Sorry for a little mistake, this is doc.innerHTML = Date();
[更新]抱歉,有一个小错误,这是
doc.innerHTML = Date();
instead of doc.innerHTML = arr.toString();
而不是
doc.innerHTML = arr.toString();
Your style is on the <span>
element. 您的样式位于
<span>
元素上。 When you use change the innerHTML, the <span>
element is replaced by the text. 当使用更改innerHTML时,
<span>
元素将替换为文本。 You need to update your code to be the following: 您需要将代码更新为以下内容:
HTML: HTML:
<p id="demo"><span id="result" class="cstyle">Result.</span></p>
and JS: 和JS:
var getDate = function() {
var doc = document.getElementById("result");
doc.innerHTML = Date();
}
This is because you are applying the font-family: "Comic Sans MS", cursive
on the element with class .cstyle
. 这是因为您正在对
.cstyle
类的元素应用font-family: "Comic Sans MS", cursive
。 When clicking on the button, you are replacing the 点击按钮时,您将替换
<span class="cstyle">Result.</span>
with a string value (without the . cstyle
class which provides the styling of your desired font). 带有字符串值(不提供提供所需字体样式的
cstyle
类)。
Just move your class .cstyle
on the parent element <p>
. 只需将类
.cstyle
移动到父元素<p>
。
<p id="demo" class="cstyle"><span >Result.</span></p>
<button type="button" onClick="getDate()">Display Data</button>
You can even leave the <span>
element, which is not needed in this case. 您甚至可以保留
<span>
元素,这种情况下不需要。
<p id="demo" class="cstyle">Result.</p>
<button type="button" onClick="getDate()">Display Data</button>
Unfortunately you are replacing the span with the cstyle with just the date. 不幸的是,您只用日期替换了cstyle。 Remember you have selected the p with id demo to insert your result so you simply replace its html using innerHTML.
记住,您已经选择了带有id demo的p来插入结果,因此您只需使用innerHTML替换其html。 If that paragraph had also the class cstyle then everything would be fine.
如果该段也具有cstyle类,那么一切都会很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.