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,因此非常感谢您提供反馈。
答案 0 :(得分: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>