Javascript 样式的错误

标签 javascript php html css styles

我的 JS 脚本向我发送了那个错误:

Uncaught TypeError: Cannot read property 'style' of null at myFunction ((index):1368) at HTMLDivElement.onclick ((index):1354) myFunction @ (index):1368 onclick @ (index):1354

这是我的代码:

function myFunction() {

  var y = document.getElementById("woocommerce_product_categories-1");
  var x = document.getElementById("shop-sidebar");

  console.log("x.style.display1");

  x.style.display = 'none';

  console.log("x.style.display");

  if (x.style.display == "none") {
    y.style.display = "none";
    x.style.position = "fixed";
    x.style.display = "block";
    x.style.zIndex = 9;
    x.style.top = "126px";
    x.style.width = "100%";
    x.style.background = "#fff";
    x.style.height = "calc(100vh - 126px)";
    x.style.overflowY = "scroll";
  } else {
    x.style.display = "none";
    x.style.zIndex = 0;
  }

  var x = document.getElementById("menu-mobile-header");
  if (x.style.position === "absolute") {
    x.style.position = "fixed";
  } else {
    x.style.position = "absolute";
  }
  var x = document.getElementById("menu-mobile-header");
  if (x.style.top === "195px") {
    x.style.top = "60px";
  } else {
    x.style.top = "195px";
  }
  var x = document.getElementById("menu-mobile-header");
  if (x.style.zIndex === "0") {
    x.style.zIndex = "9";
  } else {
    x.style.zIndex = "0";
  }


}
<?php if(is_product_category())
{ ?>

<div id="menu-mobile-header">
  <div class="menu-mobile-header" onclick="myFunction()">Filtern</div>
</div>

<?php } ?>

Console.log 向我发送带有 x.style.display1 的消息,但在第二条消息中我有错误。

我还注意到该代码可以工作但没有 php。

也许有人知道为什么我不能在 JS 中使用任何样式?

祝你有美好的一天!

最佳答案

这是因为xnull

您使用 document.getElementById 创建了 x(第 8 行),但是您没有带有 id="shop-sidebar"< 的 DOM 元素 属性。

关于Javascript 样式的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49272153/

相关文章:

java - 使用 jsp/taglibs 与模板引擎

php - Laravel foreach 变量循环作用域

javascript - jQuery:幻灯片的自定义分页

html - 如何正确使用 CSS 动画延迟来创建可折叠的 HTML 容器?

php - 将 jQuery.ajax 数据同时发送到表单提交

javascript - ECMAScript 6 负二进制文字

javascript - 在 Visual Studio 2008 中为 JavaScript 设置断点时出现问题

javascript - 如何为具有不同 id 属性的多个表单概括文件上传 Web 表单的代码?

javascript - 从卡住的父对象创建新对象

PHPUnit 找不到 PHPUnit_Extensions_Story_TestCase。缺少什么包裹?