我正在将一段代码从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.
两个问题:
如何is(':visible')
使用纯JavaScript 模拟?
我如何扩展ChocolateChip UI is()
来处理:visible
?
Pieter De Bi.. 7
作为第一个问题的答案:
在jQuery 1.3.2中,如果浏览器报告的offsetWidth或offsetHeight大于0,则元素是可见的.(源)
所以
$(element).is(":visible")
应该是一样的
(element.offsetWidth > 0 || element.offsetHeight > 0)
LeGEC.. 5
作为第二个问题的答案:
ChocolateChip UI似乎没有提供扩展选择器的方法。该函数的代码.is()
显示,当选择器为字符串时,该字符串将直接馈送到.querySelectorAll()
。
但是,您也可以将a 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)。
作为第二个问题的答案:
ChocolateChip UI似乎没有提供扩展选择器的方法。该函数的代码.is()
显示,当选择器为字符串时,该字符串将直接馈送到.querySelectorAll()
。
但是,您也可以将a 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)。
作为第一个问题的答案:
在jQuery 1.3.2中,如果浏览器报告的offsetWidth或offsetHeight大于0,则元素是可见的.(源)
所以
$(element).is(":visible")
应该是一样的
(element.offsetWidth > 0 || element.offsetHeight > 0)