使用Javascript向元素添加类
我想根据他们使用的浏览器向元素添加一个类。这就是我所拥有的:使用Javascript向元素添加类,javascript,firefox,browser,user-agent,Javascript,Firefox,Browser,User Agent,我想根据他们使用的浏览器向元素添加一个类。这就是我所拥有的: var browser = navigator.userAgent; if (browser.match("Firefox")){ $(".dollar").addClass("ff"); } 但它似乎不起作用。我做错了什么 编辑:HTML <p class="dollar">$</p> $ 因为navigator.userAgent返回 “Mozilla/5.0(Windows NT 6.1;WOW
var browser = navigator.userAgent;
if (browser.match("Firefox")){
$(".dollar").addClass("ff");
}
但它似乎不起作用。我做错了什么
编辑:HTML
<p class="dollar">$</p>
$
因为navigator.userAgent返回
“Mozilla/5.0(Windows NT 6.1;WOW64;rv:40.0)Gecko/20100101 Firefox/40.0”
当然,它与if语句中的“Firefox”不匹配,因此if语句是错误的
您可能想试试:
if (navigator.userAgent.search("Firefox/") > -1)
就像你的if一样——应该可以看到Firefox——然后使用Chrome/进行Chrome测试
[为if建议编辑]因为navigator.userAgent返回
“Mozilla/5.0(Windows NT 6.1;WOW64;rv:40.0)Gecko/20100101 Firefox/40.0”
当然,它与if语句中的“Firefox”不匹配,因此if语句是错误的
您可能想试试:
if (navigator.userAgent.search("Firefox/") > -1)
就像你的if一样——应该可以看到Firefox——然后使用Chrome/进行Chrome测试
[为if建议编辑]使用文档(DOM)就绪包装:
var browser = navigator.userAgent;
jQuery(function( $ ){ // DOM is now ready
if (browser.match("Firefox")){
$(".dollar").addClass("ff"); // and .dollar is parsed
}
});
在Firefox中测试这个示例使用文档(DOM)就绪包装:
var browser = navigator.userAgent;
jQuery(function( $ ){ // DOM is now ready
if (browser.match("Firefox")){
$(".dollar").addClass("ff"); // and .dollar is parsed
}
});
在Firefox中测试此示例请在中添加html代码,因为它不起作用吗?使用调试器浏览代码。这项工作不使用浏览器嗅探。使用功能检测。请添加html代码,因为它不工作吗?使用调试器浏览代码。这项工作不使用浏览器嗅探。使用特征检测。它适合我。字符串包含“Firefox”,所以我不明白为什么它不匹配。感谢您的回复。正如@Roko所建议的,我需要首先完全加载DOM。所以我最初的browser.match(“Firefox”)仍然可以工作,它只需要将它包装在一个函数中。我测试了你的,效果也不错。非常感谢。这对我来说很相配。字符串包含“Firefox”,所以我不明白为什么它不匹配。感谢您的回复。正如@Roko所建议的,我需要首先完全加载DOM。所以我最初的browser.match(“Firefox”)仍然可以工作,它只需要将它包装在一个函数中。我测试了你的,效果也不错。非常感谢。谢谢@Roko这工作做得很好不客气@rubytank you@Roko这工作做得很好不客气@Ruby