0

  function screenFunc(id) {
      var size = window.matchMedia("(max-width: 620px)")
      if (size.matches) { // If media query matches
        function myFunction(id) {
          var x = document.getElementById(id)
          if (x.style.display === 'none') {
            x.style.display = 'block';
          } else {
            x.style.display = 'none'
          }
        }
      }
    }
<section class="subject">
        <h2 onclick="screenFunc('intro')" class="title-toggle"> Introduction </h2>
        <p id="intro"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis laborum eligendi, nulla aliquid perspiciatis tempore cumque odit sapiente ut, reiciendis accusantium sint dolor. Ipsum eaque, quos esse incidunt, quod veniam sequi sint, voluptatem
          at quis impedit amet illum cupiditate explicabo! </p>
      </section>

我需要访问我的 HTML 中的 id 来切换段落。由于它是移动优先且响应迅速的,因此仅在最大宽度为 620 时才需要切换,因此我想删除任何大于该宽度的 javascript 切换。我可以像这样将“id”参数从父函数传递给子函数吗?这是我第一次使用 window.matchmedia,因此非常感谢您的反馈。

4

1 回答 1

2

不需要第二个功能。我认为它可能什么都不做,因为第二个函数永远不会被调用。你可以这样做:

function screenFunc(id) {
  var size = window.matchMedia("(max-width: 620px)")
  if (size.matches) { // If media query matches
      var x = document.getElementById(id)
      if (x.style.display === 'none') {
        x.style.display = 'block';
      } else {
        x.style.display = 'none'
      }
    }
}
<section class="subject">
  <h2 onclick="screenFunc('intro')" class="title-toggle"> Introduction </h2>
  <p id="intro"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis laborum eligendi, nulla aliquid perspiciatis tempore cumque odit sapiente ut, reiciendis accusantium sint dolor. Ipsum eaque, quos esse incidunt, quod veniam sequi sint, voluptatem at quis impedit amet illum cupiditate explicabo! </p>
</section>

于 2018-07-30T17:51:59.307 回答