jQuery是否有一个类似于CSS3的:target
伪类?
如果是这样,演示会很好。
谢谢!
答案 0 :(得分:5)
内置,我不这么认为,但你可以像这样偷偷摸摸:
$(location.hash);
编辑:谢谢,格雷厄姆!
另一个编辑:这是一个等同于:target
的jQuery示例。由于较旧的浏览器可能无法识别window.onhashchange
事件,并且location.hash
通常会在处理程序结束时更新锚标记的onclick
事件(在jQuery选择器期间呈现新的哈希值不可用)处理程序除非预先调用location.hash = this.href.substring(this.href.indexOf('#'));
,否则我们必须使用所点击锚点的剪切href
值作为选择器:http://jsfiddle.net/xPMzV/
答案 1 :(得分: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):
- :根
- 的:目标强>
- :第n-最后孩子
- :nth-of-type /:nth-last-of-type /:first-of-type /:last-of-type /:only-of-type
- :郎()
由于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");
});
}
});
答案 2 :(得分:1)
简单,只需:
$(window.location.hash)