使用Javascript检测URL并应用CSS [英] Detect URL with Javascript and apply CSS

查看:80
本文介绍了使用Javascript检测URL并应用CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个页面我想要应用一些CSS,但它是由CMS动态生成的。 URL保持不变,所以我想我可以把它放在模板文件的头部,将CSS添加到我想要的页面,但它不起作用。

So I have a page I want to apply some CSS to, but it is dynamically generated by the CMS. The URL remains constant, so I thought I could stick this in the head of the template file to add the CSS to the page I want, but it's not working.

<script type="text/javascript">
jQuery(document).ready(function () {
if(window.location.href.indexOf("/products.html"))
{
document.write("<style type=\"text/css\">
.category-grid li:nth-child(4)
{
margin-left:115px;
}   
</style>");
}
});
</script>

我的 document.write 声明,因为那是错误似乎发生的地方,但我无法弄明白。有什么想法?

There's probably some syntax off on my document.write statement, as that's where the error seems to occur, but I can't figure it out. Any ideas?

推荐答案

报价没有正确终止。

此外,您应延迟 document.write ,因为它会覆盖当前文档。另外,将 indexOf 的结果与 -1 进行比较。如果找不到子字符串,您之前的代码仍将注入脚本,因为 !! - 1 为真。

Also, you should not defer document.write, because it overwrites the current document. Also, compare the result from indexOf against -1. If the sub-string is not found, your previous code would still inject the script, because !!-1 is true.

您的代码可以通过以下方式修复:

Your code can be fixed in this way:

<script>
if (location.href.indexOf("dev.obtura.com/products.html") !== -1) {
    document.write("<style>" +
    ".category-grid li:nth-child(4){" +
    "    margin-left:115px;" +
    "}" +
    "</style>");
}
</script>

这篇关于使用Javascript检测URL并应用CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆