$(window).width的条件行为 [英] Conditional behaviour with $(window).width

查看:227
本文介绍了$(window).width的条件行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当窗口高于1278像素时,我想要一定的mouseenter和mouseleave行为。对于低于1278的宽度,我想禁用此切换行为,只需将2个元素设置为1状态(可见和活动)。如果浏览器的宽度超过1278,我还必须将状态重置为默认值(隐藏和非活动)。这就是我所拥有的:

I'd like a certain mouseenter and mouseleave behavior when the window is above 1278 pixels. For widths below 1278, I want to disable this toggle behavior and just set the 2 elements to 1 state (visible & active). I also have to reset the state back to default (hidden & inactive) if the browser is made wider than 1278. This is what I have:

$('section').live('mouseenter', function() {
  if ($(window).width() > 1278) {
    $(this).find('menu').removeClass('hidden');
    $(this).find('div.section-wrapper').addClass('active');
  }
}).live('mouseleave', function() {
  if ($(window).width() > 1278) {
    $(this).find('menu').addClass('hidden');
    $(this).find('div.section-wrapper').removeClass('active');
  }
});

$(document).ready(function() {
  $(window).bind('load resize orientationchange', function(){
    if ($(window).width() < 1278) {
      $('section').find('menu').removeClass('hidden');
      $('section').find('div.section-wrapper').addClass('active');
    } else {
      $('section').find('menu').addClass('hidden');
      $('section').find('div.section-wrapper').removeClass('active');
    }
  });
});

它有效,但我想知道我是否可以做一些更优雅的事情。

It works but I'm wondering if I can do something more graceful.

推荐答案

CSS媒体查询是这里的最佳选择。虽然你不会注意到改进的性能,除非你在慢速设备上,这是更快的等价物:

CSS media queries are the best option here. Though you won't notice the improved performance unless you're on a slow device, this is the faster equivalent:

@media(min-width: 1279px) {
  section:hover {
    menu.hidden {
      display: block;
      visibility: visible;
    }
    .section-container { padding: 14px; }
    .section-wrapper { border: 1px #ddd solid; }
  }
}
@media(min-width: 768px) and (max-width: 1278px) {
  menu.hidden {
    display: block;
    visibility: visible;
  }
  .section-container { padding: 14px; }
  .section-wrapper { border: 1px #ddd solid; }
}

这两个块看起来几乎相同,但它们不是。它们在悬停时以及当屏幕宽度低于1278px但宽度超过768px时强制活动外观。

The two blocks look almost identical, but they aren't. They force the "active" look upon hovering as well as when the screen is below 1278px wide but above 768px wide.

这篇关于$(window).width的条件行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆