<分区>
标签 javascript html css
<分区>
我有两个链接到 html 元素的 css 选择器。 Onmousedown javascript 应该将类更改为“closeMenuButtonActive”,onmouseup 应该等待 500 毫秒,然后将类名更改为“closeMenuButtonNotActive”。 出于某种原因,此代码无法正常工作!我尝试执行 alert(this.className);
以查看发生了什么, alert 表示正确的 closeMenuButtonNotActive。奇怪的是,我查看了检查器中的元素,类名没有改变!这是我的内联 javascript 代码:
<div id="closeMenuButton" class="closeMenuButtonNotActive" onmousedown="this.className = 'closeMenuButtonActive';" onmouseup="window.setTimeout(function(){this.className = 'closeMenuButtonNotActive';},500);">
最佳答案
那是因为this
指的是 window
关于这个功能:
window.setTimeout(function() {
// Wrong this
this.className = 'closeMenuButtonNotActive';
},500);
相反你可以这样做
var elem = this;
window.setTimeout(function() {
elem.className = 'closeMenuButtonNotActive';
},500);
如果你不想污染全局范围:
(function(elem) {
window.setTimeout(function() {
elem.className = 'closeMenuButtonNotActive';
},500);
)(this);
无论如何,为了防止出现更多难以调试的问题,您真的应该至少考虑在 HTML 中使用一个函数 <div onmouseup="doStuff(this)">
并从 javascript 代码定义 doStuff。或者更好的是,添加鼠标事件监听器指令 from the code .
关于Javascript 类名操作不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29835229/
相关文章:
javascript - Material 组件-web : How to increase width of a Tempory Drawer?
具有百分比宽度的 html 元素需要具有其内部静态内容的最小宽度
javascript - Jquery:在html页面中更改类时的平滑过渡效果
css - :last-child pseudo class confusion
javascript - 从数据表中以 json 形式从 Controller 获取数据
javascript - Angularjs – 在 ng-repeat 不适用于 http get 后初始化脚本