3

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

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

谢谢!

4

3 回答 3

5

内置的,我不这么认为,但你可以像这样 jerry-rig 一个:

$(location.hash);

编辑:谢谢,格雷厄姆

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

于 2011-12-15T22:46:55.880 回答
3

It will work in browsers that support both document.querySelectorAll() and the :target pseudo-class, and throw an error in browsers that do not (IE7 and IE8). This is because jQuery uses the browser's native document.querySelectorAll() if available, and falls back to the sizzle selector engine otherwise. Annoyingly, Sizzle does not support the :target selector:

Sizzle supports virtually all CSS 3 Selectors – this even includes some parts that are infrequently implemented such as escaped selectors (“.foo\+bar”), Unicode selectors, and results returned in document order. There are a few notable exceptions to the CSS 3 selector support (the reasoning for this decision can be found here):

  • :root
  • :target
  • :nth-last-child
  • :nth-of-type / :nth-last-of-type / :first-of-type / :last-of-type / :only-of-type
  • :lang()

Since sizzle does not support :target, jQuery will throw an error when it is used in older browsers.

Try this page in various browsers: http://jsfiddle.net/gilly3/NPNFg/

The good news is it is trivial to add a :target selector yourself:

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

Working demo: http://jsfiddle.net/gilly3/NPNFg/3/

Edit: You can get IE7 and IE8 to work with :target styles by duplicating your :target style definitions, replacing :target with .target. Note, you would have to duplicate the entire definition, because if you try to use the :target pseudo-class in the rule definition's selector, IE8 chokes on it and doesn't parse the rule at all. After duplicating your styles, use the hashchange plugin, and use this code:

$(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");
        });
    }
});

Working demo adapted from your jsfiddle: http://jsfiddle.net/gilly3/c9BvU/6/

于 2011-12-15T23:18:42.790 回答
1

简单,只需:

   $(window.location.hash)
于 2011-12-15T22:52:37.077 回答