javascript - 文本和光标样式通过 JavaScript 更改 : browser compatibility problems

标签 javascript css cross-browser

我有一个导航栏,它使用 JavaScript 来跟踪其状态并相应地更新文本和光标样式属性。这在 Firefox 26.0 中按预期工作,但在 Chrome 32.0.1700.76 中不起作用;在 Chrome 中,它似乎什么都不做。说明这一点的简短脚本是:

var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var foo_on = true;

function turn_on(x) {
    x.style = "color: #42A6FF; cursor: pointer;";
    x.onmouseover = function () { x.style = "color: #444444; cursor: pointer;"; };
    x.onmouseout = function () { x.style = "color: #42A6FF; cursor: pointer;"; };
}

function turn_off(x) {
    x.style = "color: #BBBBBB; cursor: default;";
    x.onmouseover = null;
    x.onmouseout = null;
}

function toggle(caller) {
    if((foo_on && caller == 'bar') || (!foo_on && caller == 'foo')){ return; }
    if(foo_on){        
        turn_off(foo);
        turn_on(bar);
    }
    else{        
        turn_on(foo);
        turn_off(bar);
    }
    foo_on = !foo_on;
}

function init() {
    foo_on = true;
    turn_on(foo);
    turn_off(bar);
}

window.onload = init();

我的文档布局是:

<html>
    <head>      
        <title>Test</title>        
    </head>
    <body>
        <div style='-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;' unselectable='on'> 
            <a id="foo" onclick="toggle('foo')"> FOO </a>
            <a id="bar" onclick="toggle('bar')"> BAR </a>
        </div>
        <script> {code above} </script>
    </body>
</html>

现场直播 http://jsfiddle.net/TF9X7/ .为什么这在 Chrome 中不起作用(或者 Firefox 原谅我犯了什么错误)?

最佳答案

Or do it right, and use classes …

我是 JavaScript 的新手;您能否详细说明或提供引用?

不是直接通过 JS 设置样式值,而是在 CSS 中定义它们,使用特定的类名——然后为元素设置或删除该类名:

CSS:

a { color: #BBBBBB; cursor: default; }
a.on { color: #42A6FF; cursor: pointer; }
a.on:hover { color: #444444; };

JS:

function turn_on(x) {
    x.className = "on";
}

function turn_off(x) {
    x.className = "";
}

http://jsfiddle.net/TF9X7/2/

关于javascript - 文本和光标样式通过 JavaScript 更改 : browser compatibility problems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21234571/

相关文章:

html - 如何在html中获取直线上的文本和行

javascript - 向下滚动时 Angular 隐藏标题,向上滚动时显示

javascript - 如何打开链接并将其包含在 div 中

javascript - 如何更改 Click MVC 上的按钮文本?

html - 尝试并排获取 3 张图像,并在 HTML/CSS 中使用下面的链接

css - @media 屏幕不工作

html - 搜索跨浏览器工作的回复 utf 字符箭头

javascript - 为什么我的 JS 代码在运行,而 DOM 操作还没有完成

javascript - 将 IE hack 与 JQuery css() 结合起来?

javascript - DataTables 在加载新数据后更新按钮