模拟jQuery:使用普通Javascript的可见选择器 [英] Emulating jQuery :visible selector with plain Javascript
问题描述
我正在将一段代码从jQuery转换为 ChocolateChip UI ,这段代码让我很难过由于ChocolateChip UI不支持':visible'实现是()
I am converting a piece of code from jQuery to ChocolateChip UI, and this piece of code is stumping me as ChocolateChip UI doesn't support ':visible' for its implementation of is()
if (interactive && block.is(':visible')) {
block.fadeOut(250, function() {
block.html(newContent);
block.fadeIn(750);
});
showHighlight($("#character_text"));
}
我得到的错误是:
Uncaught SyntaxError: Failed to execute query: ':visible' is not a valid selector.
两个问题:
- 如何使用纯JavaScript模拟
是(':visible')
? - 如何扩展ChocolateChip UI的
是()
处理:可见
?
- How can I emulate
is(':visible')
using plain JavaScript? - How can I extend ChocolateChip UI's
is()
to handle:visible
?
推荐答案
作为第二个问题的答案:
As an answer to your second question :
ChocolateChip UI似乎没有提供扩展的方法选择。 的代码.is()
function 表明,当选择器是一个字符串时,该字符串直接输入 .querySelectorAll()
。
ChocolateChip UI does not seem to offer a way to extend selectors. The code for the .is()
function shows that, when the selector is a string, this string is directly fed to .querySelectorAll()
.
但是,您也可以传递函数
作为参数,因此使用谓词 Pieter de Bie 指出,您可以写道:
However, you can also pass a function
as an argument, so using the predicate Pieter de Bie pointed out, you can write :
$.fn.extend({
isVisible: function(){
return this.is( function(elem){
return elem.offsetWidth > 0 || elem.offsetHeight > 0;
});
}
});
if ( $('.mySelector').isVisible() ){
....
}
另一个解决方案是使用jQuery:作者规定他们的库应该与jQuery> 2.0.3兼容(参见项目的自述。
这篇关于模拟jQuery:使用普通Javascript的可见选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!