【问题标题】:Remove the :hover event on mobile devices移除移动设备上的 :hover 事件
【发布时间】:2016-09-30 11:46:59
【问题描述】:

我在网站上运行了:hover 事件,但是当您在移动设备上使用该系统时我遇到了问题。

有没有办法在 css 或 js 中删除它?我尝试了很多东西,但我没有运气。

我尝试了modernizr.com 和媒体查询,但没有成功。

我的 sass 代码:

ul {
    li {
      padding: 20px;
       &:hover {
        background-color: $red;
        color: $black;
      }
    }
  }

媒体查询:

@media (max-width: $screen-sm-min) {
  ul {
    li {
      &:hover {
        color: inherit; 
        cursor: pointer;
      }
    }
  }
}

sass mq 变量:

$screen-sm-min: 768px;

【问题讨论】:

  • 虽然你已经尝试过媒体查询,但我还是会让你知道它是可能的。请分享你的代码
  • 我用代码编辑我的问题。
  • 为什么不只应用所需宽度的悬停样式,而不是将它们应用到所有宽度然后尝试撤消它们?

标签: javascript jquery css sass


【解决方案1】:

您可以使用 CSS 媒体查询来实现交互功能,但它们相对较新,iOS9 + 和 Android 5+:http://caniuse.com/css-media-interaction

您可以使用仅在此功能可用的情况下应用 :hover 样式

/* :hover will only work in Edge, Chrome, Safari 9+ for now  */
@media (hover: hover) {
    .your-selector:hover {
        color: red;
    }
}

或者,如果您现在想要更广泛的支持,请尽可能删除:hover

/* :hover will be removed in iOS 9+ and Android 5+  */
.your-selector:hover {
    color: red;
}
@media (hover: none) {
    .your-selector:hover {
        color: oldcolor; 
    }
}

如果您想要更广泛的支持,您需要通过 javascript 检测触摸功能。一个相当标准的方法是:

/* add a class to <html> */
var isTouch = 'ontouchstart' in window;
document.documentElement.className += isTouch?' touch ':' no-touch ';
/* only use hover when the no-touch class is present */
.no-touch {
    .your-selector:hover {
        color: red;
    }
}

在您的代码中使用最后一个解决方案:

ul {
  li {
    padding: 20px;
     .no-touch &:hover {
      background-color: $red;
      color: $black;
    }
  }
}

【讨论】:

  • 我学到了一些新东西 - 谢谢。从未将媒体查询用于交互功能 - 我将从现在开始!
  • 如果我使用带触摸屏和鼠标的笔记本电脑会怎样?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-02
  • 2016-03-31
  • 2021-03-17
  • 2020-12-09
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
相关资源
最近更新 更多