多个if语句根据URL返回css值

Multiple if statement returning css value depending on URL

本文关键字:返回 css URL if 语句 多个      更新时间:2023-09-26

脚本可以工作,但它们似乎是一个错误,导致第一个和最后一个if语句实现样式,无论它在哪个页面上。中间的if语句不显示。

我也尝试过在每个if语句后中断并返回,但这完全阻止了脚本,并且不会在页面上显示任何内容。

window.onload = function()
{ 
var ThisStyle = "background-color: #4C4C4C; color: #fff; -webkit-border-top-right-radius: 15px; -webkit-border-bottom-right-radius: 15px; -moz-border-radius-topright: 15px; -moz-border-radius-bottomright: 15px; border-top-right-radius: 15px; border-bottom-right-radius: 15px;"
if (document.URL.indexOf("index.php"))
{
    document.getElementById("home-nav").style.cssText = ThisStyle;
}
else if (document.URL.indexOf("about.php"))
{
    document.getElementById("about-nav").style.cssText = ThisStyle;
}
else (document.URL.indexOf("products.php"))
{
    document.getElementById("products-nav").style.cssText = ThisStyle;
}
}

有人知道我做错了什么吗?

这里有多个问题,正如我前面提到的,if在最后一条语句中丢失,如果找不到该项,indexOf()也将返回-1,这是一个真实值,所以你的第一个条件总是真

更合适的解决方案是使用类

.active {
    background-color: #4C4C4C;
    color: #fff;
    -webkit-border-top-right-radius: 15px;
    -webkit-border-bottom-right-radius: 15px;
    -moz-border-radius-topright: 15px;
    -moz-border-radius-bottomright: 15px;
    border-top-right-radius: 15px;
    border-bottom-right-radius: 15px;
}

然后

window.onload = function () {
    var url = document.URL,
        id;
    if (url.indexOf("index.php") > -1) {
        id = 'home-nav';
    } else if (url.indexOf("about.php") > -1) {
        id = 'about-nav';
    } else if (url.indexOf("products.php") > -1) {
        id = 'products-nav';
    }
    if (id) {
        var el = document.getElementById(id);
        if (el.classList) {
            el.classList.add('active')
        }else{
            el.className+= ' active'
        }
    }
}

演示:Fiddle

你错过了indexOf的比较,如果你得到-1或0,我认为即使你不想,它也会进入条件,试试这个:

window.onload = function ()
{
    var ThisStyle = "background-color: #4C4C4C; color: #fff; -webkit-border-top-right-radius: 15px; -webkit-border-bottom-right-radius: 15px; -moz-border-radius-topright: 15px; -moz-border-radius-bottomright: 15px; border-top-right-radius: 15px; border-bottom-right-radius: 15px;"
    if (document.URL.indexOf("index.php") > -1)
    {
        document.getElementById("home-nav").style.cssText = ThisStyle;
    }
    else if (document.URL.indexOf("about.php") > -1)
    {
        document.getElementById("about-nav").style.cssText = ThisStyle;
    }
    else
        (document.URL.indexOf("products.php") > -1)
    {
        document.getElementById("products-nav").style.cssText = ThisStyle;
    }
}

indexOf如果未找到,则返回-1。这将是事实。

您需要添加!= -1 的检查

if (document.URL.indexOf("xxxx") != -1) {