【问题标题】:Multiple inline styles with JS, how to set fallback?JS的多个内联样式,如何设置回退?
【发布时间】:2025-12-10 00:30:01
【问题描述】:

所以如果我要在 css 中将它写成一个类,我会得到类似的东西:

.cursorChange {
    cursor: move; /*IE*/
    cursor: grabbing; /*Mozilla*/
    cursor: -webkit-grabbing; /*Chrome*/
}

但是,我想在抓取元素时将这些样式与 javascript 内联应用。现在是这样的一行:

document.getElementById('foo').style.cursor = "move";

显然可以,但是如何向该节点添加多个值?如果我只写grabbing,IE没有fallback,mozzila也不识别,有没有办法在这里添加多个值?

附:无法更改整个样式字符串,因为它的光标不止于此。由于 css 的编写方式,我需要它是内联的,而不是类。

【问题讨论】:

  • 本身不是解决方案,但 this 可能会让您感兴趣。
  • " 由于 css 的编写方式,我需要它是内联的,而不是类。" 你能详细说明一下吗?这听起来很可疑。
  • @JLRishe 光标属性应用于已经定义了为其设置光标的 css 类并且没有 ID 的元素,因此内联是在拖动时覆盖光标的最佳解决方案正在发生。
  • @Scipion 在这种情况下不适用,无法设置整个样式字符串,还有其他元素可能存在也可能不存在,具体取决于很多因素。

标签: javascript css


【解决方案1】:

这样的事情怎么样:

if(navigator.userAgent.indexOf("Chrome") != -1 ){ // Chrome
        document.getElementById('foo').style.cursor = "-webkit-grabbing";
}else if(navigator.userAgent.indexOf("Firefox") != -1 ){ //FireFox
        document.getElementById('foo').style.cursor = "grabbing";
}else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )){ //IE
       document.getElementById('foo').style.cursor = "move";
}    

【讨论】:

  • “P.S. 无法更改整个样式字符串,因为它的光标不止于此。”
  • 感谢@JLRishe,编辑并更改了我的答案。
【解决方案2】:

您可以尝试以下方式:

var isIE = /*@cc_on!@*/false || !!document.documentMode;
var isMozilla = typeof InstallTrigger !== 'undefined';  
var isChrome = !!window.chrome && !!window.chrome.webstore;

if(isIE) {
    document.getElementById('foo').style.cursor = "move";
}
if(isMozilla) {
    document.getElementById('foo').style.cursor = "grabbing";
}
if(isChrome) {
    document.getElementById('foo').style.cursor = "-webkit-grabbing";
}

您还可以从这里获得更多浏览器选项:How to detect Safari, Chrome, IE, Firefox and Opera browser?

【讨论】:

  • 感谢所有浏览器的链接,因为我觉得这个答案可能会帮助更多的人。你们俩都得到+1。那我是不是解释说没有办法通过js内联设置多个节点?
最近更新 更多