如何在首页及搜索结果页隐藏指定CSS类?求正确JS代码
解决方案
没问题,我来帮你修正这段代码!你之前的写法有两个问题:一是两个if语句没有用逻辑连接符组合,二是用严格相等==判断URL会漏掉带查询参数的product-search页面(比如?s=test这类)。
下面是正确的实现代码,同时还做了防报错优化(避免找不到元素时控制台报错):
<script> // 获取目标元素 const targetElement = document.getElementsByClassName("rh-flex-left-align")[0]; // 判断当前页面是否是首页,或者路径包含/product-search/ const isHomePage = window.location.href === "https://www.comparer-acheter.fr/"; const isProductSearchPage = window.location.pathname.includes("/product-search/"); if (targetElement && (isHomePage || isProductSearchPage)) { targetElement.style.display = 'none'; } </script>
代码说明:
- 用
window.location.pathname来判断路径部分,这样不管后面带多少查询参数,只要路径包含/product-search/就能匹配到 - 新增了元素存在性判断
targetElement && ...,避免页面没有这个元素时控制台抛出错误 - 用逻辑或
||把两个条件组合起来,满足任意一个就执行隐藏操作
额外优化建议(可选):
如果你的项目里有自定义CSS类,推荐用添加/移除类的方式来控制显示,比直接修改style.display更灵活,比如:
/* 先在CSS里定义隐藏类 */ .hidden { display: none !important; }
然后JS代码改成:
<script> const targetElement = document.getElementsByClassName("rh-flex-left-align")[0]; const isHomePage = window.location.href === "https://www.comparer-acheter.fr/"; const isProductSearchPage = window.location.pathname.includes("/product-search/"); if (targetElement) { if (isHomePage || isProductSearchPage) { targetElement.classList.add("hidden"); } else { targetElement.classList.remove("hidden"); } } </script>
这样如果后续需要调整隐藏的样式(比如改成visibility: hidden),直接修改CSS即可,不用动JS代码。
内容的提问来源于stack exchange,提问作者flo-uxdev
相关产品推荐
相关产品推荐

