javascript - :touch CSS pseudo-class or something similar?

标签 javascript jquery html css mobile

我正在尝试制作一个按钮,这样当用户单击它时,它会在按住鼠标按钮时更改其样式。如果在移动浏览器中触摸它,我还希望它以类似的方式更改其样式。对我来说看似显而易见的事情是使用 CSS :active 伪类,但这没有用。我试过 :focus,但也没有用。我试过 :hover,它似乎有效,但在我将手指从按钮上移开后它保持了样式。所有这些观察都是在 iPhone 4 和 Droid 2 上进行的。

有什么方法可以在移动浏览器(iPhone、iPad、Android 和其他浏览器)上复制这种效果?现在,我正在做这样的事情:

<style type="text/css">
    #testButton {
        background: #dddddd;
    }
    #testButton:active, #testButton.active {
        background: #aaaaaa;
    }
</style>

...

<button type="button" id="testButton">test</button>

...

<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.1.min.js'></script>
<script type='text/javascript'>
    $("*").live("touchstart", function() {
      $(this).addClass("active");
    }).live("touchend", function() {
      $(this).removeClass("active");
    });
</script>

:active 伪类用于桌面浏览器,active 类用于触摸浏览器。

我想知道是否有更简单的方法来做到这一点,而不涉及 Javascript。

最佳答案

W3C 规范中没有:touch 这样的东西,http://www.w3.org/TR/CSS2/selector.html#pseudo-class-selectors

:active 应该可以,我想。

:active/:hover 伪类的顺序对其正常运行很重要。

引用上面的链接

交互式用户代理有时会更改呈现以响应用户操作。 CSS 为常见情况提供了三个伪类:

  • The :hover pseudo-class applies while the user designates an element (with some pointing device), but does not activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents not supporting interactive media do not have to support this pseudo-class. Some conforming user agents supporting interactive media may not be able to support this pseudo-class (e.g., a pen device).
  • The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it.
  • The :focus pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).

关于javascript - :touch CSS pseudo-class or something similar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6063308/

相关文章:

javascript - 从单个 HTTP 请求生成多个 HTTP 请求 Angular 2

javascript - 按小数点排序数组然后按字符串排序 - Javascript

html - 如何在屏幕 HTML 中制作 <div> 滚动条?

javascript - HTML大图性能问题

html - 阿拉伯语单词仅在 Google Chrome 中单独显示 - MacOS

javascript - 编码数据以发送到javascript

javascript - 从对象和数组创建对象数组

php - 选择多行放入数组并通过 AJAX 发送它们

jquery - 如何重新排列 Django 数据库中保存对象的顺序

javascript - JQuery 设置 asp 文本框的值并在回传到服务器时获取值