【问题标题】:Emulating jQuery :visible selector with plain Javascript使用纯 Javascript 模拟 jQuery:可见选择器
【发布时间】:2013-12-15 08:44:04
【问题描述】:

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

【问题讨论】:

  • if(document.getElementById("elementId").style.visibility=="visible"){ // 做点什么 }
  • 我认为这不起作用,因为:visible 是 jQuery 的扩展。因此,您可能会遇到与其他选择器相同的问题。 jQuery 实际上做了几件事来确定一个元素是否可见,这在文档中进行了解释:api.jquery.com/visible-selector.
  • @AdnanK:这还不够。该元素可能通过样式表设置样式,并且可能没有visibility 规则集,但仍然可见。
  • "在 jQuery 1.3.2 中,如果浏览器报告的 offsetWidth 或 offsetHeight 大于 0,则元素可见"

标签: javascript jquery chocolatechip-ui


【解决方案1】:

作为第一个问题的答案:

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

所以

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

应该和

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

【讨论】:

    【解决方案2】:

    作为第二个问题的答案:

    ChocolateChip UI 似乎没有提供扩展选择器的方法。 The code for the .is() function shows that, when the selector is a string, this string is directly fed to .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 兼容(参见the project's Readme)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多