模拟jQuery:使用纯Javascript的可见选择器

Emulating jQuery :visible selector with plain Javascript

本文关键字:选择器 Javascript jQuery 模拟      更新时间:2023-12-16

我正在将一段代码从jQuery转换为ChocolateChip UI,这段代码让我很困惑,因为ChocolateChip UI不支持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. 

两个问题:

  1. 如何使用纯JavaScript模拟is(':visible')
  2. 如何扩展ChocolateChip UI的is()以处理:visible

作为第一个问题的答案:

在jQuery 1.3.2中,如果浏览器报告的offsetWidth或offsetHeight大于0,则元素可见。(来源)

所以

$(element).is(":visible")

应与相同

(element.offsetWidth > 0 || element.offsetHeight > 0)

作为第二个问题的答案:

ChocolateChip UI似乎没有提供扩展选择器的方法。.is()函数的代码显示,当选择器是一个字符串时,该字符串将直接馈送到.querySelectorAll()

然而,您也可以传递一个function作为参数,因此使用Pieter de Bie指出的谓词,您可以编写:

$.fn.extend({
   isVisible: function(){
       return this.is( function(elem){
           return elem.offsetWidth > 0 || elem.offsetHeight > 0;
       });
   }
});
if ( $('.mySelector').isVisible() ){
    ....
}

另一个解决方案是使用jQuery:作者规定他们的库应该与jQuery>2.0.3兼容(请参阅项目的Readme)。