【问题标题】:Does jQuery have a :target pseudo-class similar to CSS3?jQuery 是否有类似于 CSS3 的 :target 伪类?
【发布时间】:2012-01-21 14:14:25
【问题描述】:

jQuery 是否有类似于 CSS3 的 :target 伪类?

如果是这样,演示会很好。

谢谢!

【问题讨论】:

  • 我认为你不能选择伪类。
  • 我很难理解 :target 概念如何与 jQuery 一起使用。
  • @lonesomeday 我也是!只是好奇是否有旧版浏览器的后备方案?

标签: javascript jquery css pseudo-class


【解决方案1】:

内置,我不这么认为,但你可以像这样偷工减料:

$(location.hash);

编辑:谢谢,格雷厄姆

另一个编辑:这是一个等效于 :target 的 jQuery 示例。由于较旧的浏览器可能无法识别window.onhashchange 事件,并且location.hash 通常在锚标记的onclick 事件的处理程序末尾更新(在处理程序期间呈现新的哈希对jQuery 选择器不可用,除非location.hash = this.href.substring(this.href.indexOf('#'));被预先调用),我们必须使用被点击的锚点的剪辑href值作为选择器:http://jsfiddle.net/xPMzV/

【讨论】:

  • 这看起来很有趣。能否提供如下演示:jsfiddle.net/Daniel_Hug/c9BvU
  • 见下文 - 您不需要前缀“#”,因为哈希属性包含文字哈希符号。
  • 啊,没错。我已经习惯于从location.hash 中剥离# 字符,以至于有时我会忘记它的存在。很好的收获。
【解决方案2】:

简单,做吧:

   $(window.location.hash)

【讨论】:

    【解决方案3】:

    它将在同时支持document.querySelectorAll() :target 伪类的浏览器中工作,并在不支持的浏览器(IE7 和 IE8)中抛出错误。这是因为 jQuery 使用浏览器的原生 document.querySelectorAll()(如果可用),否则回退到 sizzle 选择器引擎。烦人,Sizzle does not support the :target selector

    Sizzle 几乎支持所有CSS 3 Selectors - 这甚至包括一些不经常实现的部分,例如转义选择器(“.foo\+bar”)、Unicode 选择器和按文档顺序返回的结果。 CSS 3 选择器支持有一些值得注意的例外(这个决定的原因可以是found here):

    • :根
    • :目标
    • :nth-last-child
    • :nth-of-type / :nth-last-of-type / :first-of-type / :last-of-type / :only-of-type
    • :lang()

    由于sizzle不支持:target,jQuery在旧浏览器中使用时会报错。

    在各种浏览器中试试这个页面:http://jsfiddle.net/gilly3/NPNFg/

    好消息是自己添加:target 选择器很简单:

    $.expr[":"].target = function (node) {
        var t = location.hash.substr(1);
        return t && node.id == t || node.name == t;
    }
    

    工作演示:http://jsfiddle.net/gilly3/NPNFg/3/

    编辑:您可以通过复制您的:target 样式定义,将:target 替换为.target,使IE7 和IE8 与:target 样式一起使用。请注意,您必须复制整个定义,因为如果您尝试在规则定义的选择器中使用 :target 伪类,IE8 会阻塞它并且根本不解析规则。复制样式后,使用hashchange 插件,并使用以下代码:

    $(function () {
        try {
            $(":target");
        }
        catch (err) {
            $.expr[":"].target = function (node) {
                var t = location.hash.substr(1);
                return t && node.id == t || node.name == t;
            }
            $(window).hashchange(function () {
                $(".target").removeClass("target");
                $(":target").addClass("target");
            });
        }
    });
    

    工作演示改编自your jsfiddle:http://jsfiddle.net/gilly3/c9BvU/6/

    【讨论】:

      猜你喜欢
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 2012-05-01
      • 1970-01-01
      • 2014-05-02
      • 2012-10-06
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多