如何根据 URL 设置样式?

时间:2021-04-09 18:25:40

标签: javascript php

我有一个显示在整个屏幕上的包装器,我想要它,所以如果我在我的 URL 中输入 ?display=0,包装器将随着 PHP 或 JavaScript 消失。我已经搜索了 2 个小时,这些是我找到的东西:

$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if($host == 'http://example.com/home?display=0') { ... }
if(location.hash == "") { ... }
if($_GET['display' == 1]) { ... }

但它们都不起作用,那么有没有任何方法可以在 PHP 或 JavaScript 中执行此操作?

2 个答案:

答案 0 :(得分:2)

您可以将 URLSearchParams 与它的 has 方法结合使用:

const urlParams = new URLSearchParams(window.location.search);
const display = urlParams.has('display');

if (display) {
  // Do something here
}

答案 1 :(得分:1)

你做的事情很接近。

if($_GET['display' == 1]) { ... }
                 ^     ^

你有一个相当严重的错字,你放错了 $_GET 数组的右括号。

把上面的改成这样应该会产生一些结果;

if($_GET['display'] == 1 ) { ... }

虽然我个人会检查一下是否设置了“显示”,所以你最终会得到类似的东西;

if ( isset( $_GET['display'] ) ) {
    // The URL included a ?display= parameter
    if ( $_GET['display'] == 1 ) { ... }

}else{
    // Default behaviour if there is no ?display= in the URL
}

如果你不做这样的检查,如果有人打开没有在 URL 中添加 ?display= 位的页面,PHP 将抛出“未定义索引:显示”错误。

相关问题