在多次发生的鼠标事件上将 className 添加到主体?
我正在向 body 标记添加一个额外的 className,但是该 className 已被添加多次...有关如何避免这种情况的一些帮助将非常受欢迎!
谢谢
<html>
<head>
<style type="text/css">
.defaultText {
font-size:100%;
}
.myNewClass {
font-size:150%;
color:red;
}
</style>
<script type="text/javascript">
<!--
var state;
window.onload=function() {
obj=document.getElementsByTagName('body')[0];
state=(state==null)?' defaultText':state;
obj.className+=state;
document.getElementById('addClass').onclick=function() {
obj.className+=(obj.className==' myNewClass')?' defaultText':' myNewClass';
state=obj.className;
}
}
-->
</script>
</head>
<body class="thisClassMustStay">
<div>My text here</div><br />
<a href='#' id="addClass">toggle class</a></div>
</body>
</html>
I am adding an additional className to the body tag, however the className is being added multiple times... some help on how to avoid this would be very welcome!
Thanks
<html>
<head>
<style type="text/css">
.defaultText {
font-size:100%;
}
.myNewClass {
font-size:150%;
color:red;
}
</style>
<script type="text/javascript">
<!--
var state;
window.onload=function() {
obj=document.getElementsByTagName('body')[0];
state=(state==null)?' defaultText':state;
obj.className+=state;
document.getElementById('addClass').onclick=function() {
obj.className+=(obj.className==' myNewClass')?' defaultText':' myNewClass';
state=obj.className;
}
}
-->
</script>
</head>
<body class="thisClassMustStay">
<div>My text here</div><br />
<a href='#' id="addClass">toggle class</a></div>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一次运行代码时,声明我们未定义,因此最好在声明它时将其设置为null,或者将上面的内容更改为:
鉴于第一次运行时表达式将计算为 true,然后 state 将设置为
'defaultText'
。请注意,字符串的开头有一个空格。在某些浏览器中,该空格将被删除,而在其他浏览器中它将被保留,因此最好将其删除。此时,“defaultText”将被添加到 body 元素的类列表中。同样,前导空格可能会出现问题,最好通过强大的 hasClass、addClass 和 removeClass 函数来处理(它们并不是特别难编写)。
使用上面建议的函数,这可能是:
。
您需要 has/add/removeClassname 函数的帮助,请询问。
The first time the code is run, state us undefined so it would be better to either set it to null when declaring it or change the above to:
Given that the first time it is run the expression will evaluate to true, then state will be set to
' defaultText'
. Note that there is a space at the start of the string. In some browsers, this space will be removed and in others it will be kept, so much better to remove it.At this point, 'defaultText' will be added to the list of classes on the body element. Again there may be issues with leading spaces that are best dealt with by robust hasClass, addClass and removeClass functions (they aren't particularly difficult to write).
With functions suggested above, this could be:
.
If you need help with has/add/removeClassname functions, just ask.
我使用这个函数(对于没有 jQuery 的网站)。
另一个解决方案是保留一个全局变量来记住您是否添加了该类,或者编写一个函数来检查它:
I use this function (for sites where I don't have jQuery).
Another solution would be to keep a global to remember if you have added the class, or write a function to check it: