2

这看起来很简单..但它仍然无法正常工作。

如果你把类 .normal 放在 .hightlight 上面,我就可以工作了。但我不会改变这里的风格。只有位置。这没有任何意义..

我似乎无法在此处粘贴 html 代码,所以我必须分块进行。我附上了所有代码的快照。

确保您有一个空的 html 页面。文档类型无关紧要。我在不同的文档类型上对其进行了测试,但它仍然无法正常工作。

这是在标题之后的样式块内

.highlight { color:black; background-color:yellow; }
.normal {  color:white; background-color: blue; }

在此之后,我有一个带有最新 jquery 代码源的脚本标签 http://code.jquery.com/jquery-latest.min.js

在这之后是一个脚本块,在这里:

$(document).ready(function () {
  $('#maindiv').css('cursor', 'pointer');
  $('#maindiv').click(function () {
    //alert("click");
   // $(this).toggleClass("highlight"); //this does not work!
   // $(this).addClass('highlight'); //this does not work!

   // $(this).attr("class", "highlight"); //this works
   // $(this).css("background", "yellow"); this works

    // the javascript way to do this works also fine.
    // var element = document.getElementById('maindiv');
    // element.setAttribute("class", "highlight");
});

});

在 body ap 标签内,idname 为“maindiv”,类为“normal”

带文字点击这里。

好的,我等不及有人尝试这个了..这太疯狂了,因为所有其他方式的工作。但只有 .addClass 和 .toggleClass 不能正常工作

因为我是新用户,所以无法在此处附上完整代码的快照,但您可以在以下网址下载: http ://www.bckan.nl/temp/jquerybug.jpg

4

2 回答 2

2

顾名思义, addClass 和 toggleClass 只是添加类,这意味着您的元素仍然具有 .normal 可能比 .highlight 具有更高的优先级,因此您的颜色更改不适用。检查 DOM,您会看到该类已添加。尝试用 .highlight 替换 .normal 而不是在 CSS 中添加 .highlight 或将 .normal 放在 .highlight 上。您也可以将 !important 添加到 .highlight 的属性中,但不建议这样做。

于 2012-03-04T18:07:01.803 回答
2

尝试:

$(document).ready(function () {
    $('#maindiv').css('cursor', 'pointer');
    $('#maindiv').on('click', function() {
        $(this).toggleClass("highlight").toggleClass('normal');
    });
});  

没有尝试您的代码,但我假设它可以很好地添加类,但是由于您从不删除“普通”类,因此不会覆盖 css。

同样为了优化,请尝试在您的 javascript 中将 .css 保持在最低限度。将 maindivs 光标设置为指针可以在 .css 文件中轻松设置。并避免使用 .click / .live / .bind 等,它们已被弃用,它们都链接到新的 .on 函数。因此,只需直接使用 .on 即可。

哦,在你的 CSS 中添加 !important 会起作用,但这也是你应该尽量避免的事情,只会让你以后更难。

于 2012-03-04T18:10:07.593 回答