我有一个导航栏,它使用 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 = "";
}
关于javascript - 文本和光标样式通过 JavaScript 更改 : browser compatibility problems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21234571/