JS的媒体查询

时间:2019-09-14 11:27:13

标签: javascript jquery wordpress

我正在尝试为此脚本设置媒体查询,但是没有运气。谁能指出我正确的方向?

<script>

var mq = window.matchMedia( "(min-width: 1024px)" );

if (mq.matches) {
   $(".number-<?php echo $counter; ?>").hover(function () {
     $(".section-<?php echo $section; ?> #hover-button-<?php echo $counter; ?>").stop().slideToggle();
     return false;
 });
}
else {

}
 </script>

2 个答案:

答案 0 :(得分:0)

尝试onchange的{​​{1}}事件

matchMedia
var mq = window.matchMedia("(min-width: 1024px)");

function mediaChange() {
  console.log(mq.matches)
  
  if (mq.matches) {
    $(".number-1").hover(function() {
      $(".section-1 #hover-button-1").stop().slideToggle();
      return false;
    });
  } else {
    $(".number-1").off('mouseenter mouseleave')
  }
  
}
mediaChange();

mq.onchange = mediaChange;

注意:以<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="number-1"> hover me </div> <div class="section-1"> <div id="hover-button-1"> toggle </div> </div>模式(“运行”按钮的右侧)查看演示

答案 1 :(得分:0)

似乎这可以使用最大宽度而不是最小宽度

<script>

var mq = window.matchMedia( "(max-width: 1024px)" );

if (mq.matches) {

}

else {

   $(".number-<?php echo $counter; ?>").hover(function () {
     $(".section-<?php echo $section; ?> #hover-button-<?php echo $counter; ?>").stop().slideToggle();
     return false;
    });

}
 </script>