在 JavaScript 中使用媒体查询或在 CSS 中使用 if/else 语句

Using media queries in JavaScript or if/else statements in CSS

我正在构建一个带有可自定义打印的网页 settings.What 发生的情况是,每当单击打印按钮时,都会打开一个对话框(我使用 onclick 属性和一些 js)。对话框有一些复选框,名称如下:

所以,我想要的是,只要用户单击复选框,链接的项目就会从 @media print 查询中删除。

所以,我能想到的方法是在JavaScript中使用媒体查询或者在css中使用条件语句。

是否可以或需要其他语言?

我建议的是 adding/removing 类 项目,并将它们包含在您的印刷品中 CSS。可以像这样简单:

.hidden {
  display: none;
}

然后,在你的 JavaScript:

document.querySelector('.comments').classList.add('hidden');

另请参阅:https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

您可以使用 :checked:

@media print {
  .checkbox-class:checked + .remove-me {
    display: none;
  }
}

记住带有 class .remove-me 的元素应该是相邻的兄弟元素。像这样:

<label for="checkbox-id">Click Me</label>
<input type="checkbox" id="checkbox-id" class="checkbox-class">

<div class="remove-me">
  Lorem ipsum dolor sit amet consectetur adipisicing elit.
</div>

在 Codepen 上查看它的运行情况:Editor View Debug Mode

工作:

  • 单击更新打印信息按钮更新打印信息,然后单击提交。

  • 关闭模态后点击打印按钮查看变化。

我希望这段代码将来也能帮助到很多用户。

祝大家好运。

function update_print()
{
  var style = "<style>@media print {";
    if (document.getElementById('remove_menu').checked)
    {
        style += ".menu { display: none; }";
    }
    if (document.getElementById('remove_sidebars').checked)
    {
        style += ".sidebars { display: none; }";
    }
    if (document.getElementById('remove_links_buttons').checked)
    {
        style += ".links_buttons { display: none; }";
    }
    if (document.getElementById('remove_comments').checked)
    {
        style += ".comments { display: none; }";
    }
    style += "}</style>";
    document.getElementById("div_for_style").innerHTML = style;
  $('#myModal').modal('hide');
}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<div id="print_box">
    <p class="menu">This is Menu</p>
    <p class="sidebars">This is Sidebar</p>
    <p class="links_buttons">This is Links & Buttons</p>
    <p class="comments">This is Comments</p>
</div>

<style>
@media print {
  .hide_while_print
  {
      display: none;
  }
}
</style>

<div class="container">
  <div class="hide_while_print">
  <button type="button" class="btn btn-info btn-md" data-toggle="modal" data-target="#myModal">Update Print Info</button>
  <button type="button" class="btn btn-info btn-md" onclick="window.print();">Print</button>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">

  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">&times;</button>
      <h4 class="modal-title">Print Information</h4>
    </div>
    <div class="modal-body">
        <input type="checkbox" id="remove_menu" /> <label for="remove_menu">Remove Menu</label>
        <br />
        <input type="checkbox" id="remove_sidebars" /> <label for="remove_sidebars">Remove sidebars</label>
        <br />
        <input type="checkbox" id="remove_links_buttons" /> <label for="remove_links_buttons">Remove Links & Buttons</label>
        <br />
        <input type="checkbox" id="remove_comments" /> <label for="remove_comments">Remove Comments</label>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <input type="button" class="btn btn-success btn-sm" onclick="update_print();" value="Submit" />
    </div>
  </div>
  
</div>
</div>

<div id="div_for_style"></div>

作为对 的补充回答:提供的代码片段可以从重构中受益,以避免常见的陷阱:

  1. Do not use 内联事件属性,现代方法是使用 addEventListener 代替(如果你绝对 必须 支持旧浏览器,利用 polyfills 和 bundlers,但不要那样写你的源代码)。
  2. 通过避免字符串连接和 if 语句集使代码易于维护。有一种本地方法可以修改 Element 类 - 通过 classList property exposing DOMTokenList 方法,例如 addremove.
  3. 避免使用 innerHTML 更新节点(例如,请参阅 here for details) and element styles (you can use style 属性 以编程方式更新特定值)。

下面是处理上述问题的修改后的代码片段(请注意 HTML 标记也发生了变化):

(() => {
  const $ = (selector) => document.querySelector(selector);
  const $$ = (selector) => document.querySelectorAll(selector);

  const submitBtn = $("#submit");
  const modal = $("#myModal");
  const inputs = $$("input[type=checkbox]");
  const hideClass = "hide_while_print";

  submitBtn.addEventListener("click", (event) => {
    inputs.forEach(({
      id,
      checked
    }) => {
      const {
        classList
      } = $(`.${id.replace("remove_", "")}`);
      checked ? classList.add(hideClass) : classList.remove(hideClass);
    });

  });

  $("#print").addEventListener("click", () => window.print());
})();
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<div id="print_box">
  <p class="menu">This is Menu</p>
  <p class="sidebars">This is Sidebar</p>
  <p class="links_buttons">This is Links & Buttons</p>
  <p class="comments">This is Comments</p>
</div>

<style>
  @media print {
    .hide_while_print {
      display: none;
    }
  }
</style>

<div class="container">
  <div class="hide_while_print">
    <button type="button" class="btn btn-info btn-md" data-toggle="modal" data-target="#myModal">Update Print Info</button>
    <button id="print" type="button" class="btn btn-info btn-md">Print</button>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Print Information</h4>
      </div>
      <div class="modal-body">
        <input type="checkbox" id="remove_menu" /> <label for="remove_menu">Remove Menu</label>
        <br />
        <input type="checkbox" id="remove_sidebars" /> <label for="remove_sidebars">Remove sidebars</label>
        <br />
        <input type="checkbox" id="remove_links_buttons" /> <label for="remove_links_buttons">Remove Links & Buttons</label>
        <br />
        <input type="checkbox" id="remove_comments" /> <label for="remove_comments">Remove Comments</label>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-success" data-dismiss="modal" id="submit">Submit</button>
      </div>
    </div>

  </div>
</div>


在代码片段中,我隐藏了 $ 以使用 DOM API 定义轻量级实用程序。如果您不使用 Bootstrap(JQuery 作为 hard dependency),$$$ 实用程序可以让您避免加载 JQuery 只到 select 个元素。