【问题标题】:How do you add pseudo classes to elements using jQuery?如何使用 jQuery 向元素添加伪类?
【发布时间】:2012-09-26 07:09:00
【问题描述】:

在 CSS 中,当您将鼠标悬停在元素上时,您可以使用 :hover 伪类为其指定视图:

.element_class_name:hover {
    /* stuff here */
}

如何使用 jquery 添加或“打开”这个伪类?通常在 jQuery 中,如果你想添加一个你会做的类:

$(this).addClass("class_name");

我尝试过“悬停”,但这实际上是在元素中添加了一个名为“悬停”的类。

如果有人知道要写什么,请告诉我!谢谢!

【问题讨论】:

标签: jquery css pseudo-class


【解决方案1】:

您不能强制使用 jQuery 应用某个伪类。这不是伪类(尤其是动态伪类)的工作方式,因为它们被设计为基于无法通过 DOM 表达的信息进行选择 (spec)。

您必须指定要使用的另一个类,然后使用 jQuery 添加该类。像这样的:

.element_class_name:hover, .element_class_name.jqhover {
    /* stuff here */
}

$(this).addClass("jqhover");

或者,您可以寻找.element_class_name:hover 规则并使用jQuery 本身添加该类,而无需将其硬编码到您的样式表中。不过原理是一样的。

【讨论】:

    【解决方案2】:

    我认为使用 jQuery 或 javascript 无法做到这一点。

    你可以在这两个问题中找到相同的答案:

    1. setting-css-pseudo-class-rules-from-javascript
    2. css-pseudo-classes-with-jquery

    【讨论】:

      【解决方案3】:

      在页面上制作一个div

      <div id="Style">
        <style>
          .element_class_name:hover {
            /* stuff here */
          }
        </style>
      </div>
      

      然后以编程方式对样式进行硬编码,即,

      $("#Style").find("style").prepend("#" + this.id + ":hover, ");
      

      不幸的是,您调用它的元素必须有一个 id。

      $("body").children().click(function(){
        $("#Style").find("style").prepend("#" + this.id + ":hover, ");
      });
      /* demo */
      * {
        transition: opacity 1s;
      }
      <!DOCTYPE html>
      <html>
        <head>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        </head>
        <body>
          <div id="Style">
            <style>
              .element_class_name:hover {
                opacity: 0 !important;
              }
            </style>
          </div>
      
          <button id="btn1">Add hover class here</button>
          <button id="btn2">Add hover class here too</button>
          <p id="Note">
            To use this though, you'll have to assign an id to that particular element though.
          </p>
        </body>
      </html>

      【讨论】:

        【解决方案4】:

        jQuery 有一个hover() 函数,如下所示:https://www.w3schools.com/jquery/event_hover.asp

        对于:hover pollyfill,这是一个非常好的功能。

        $(selector).hover(inFunction,outFunction)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-11
          相关资源
          最近更新 更多