已更新,见下文...
我在为此搜索纯 javascript 解决方案时来到这里......但我希望有人会喜欢我的 jquery 版本。
这里有两个函数,它们的工作方式略有不同,但性能差异很小。我没有测量它,但是根据对jsperf“每个 vs 过滤器”的测试,.each()
版本稍微快一些。
尽管如此,我还是喜欢这个.filter()
版本,因为它是如此简短和清晰。
$.fn.isfixed = function(){
var el = $(this);
var all = el.add(el.parents());
return all.filter(function(){
return $(this).css("position") === "fixed";
}).length > 0;
};
$.fn.isfixed = function(){
var el = $(this);
var all = el.add(el.parents());
var ret = false;
all.each(function(){
if ($(this).css("position") === "fixed") {
ret = true;
return false;
}
});
return ret;
};
用法是$('path > to > your > element').isfixed()
和返回true
或false
更新
这是纯javascript版本。事实证明,检测el.style.position
(固定/绝对/相对)不起作用,不知道为什么,但window.getComputedStyle(el)...
确实如此。
var isfixed = function(elm) {
var el;
if (typeof elm === 'object') el = elm[0] || elm;
else if (typeof elm === 'string') el = document.querySelector(elm);
while (typeof el === 'object' && el.nodeName.toLowerCase() !== 'body') {
if (window.getComputedStyle(el).getPropertyValue('position').toLowerCase() === 'fixed') return true;
el = el.parentElement;
}
return false;
};
它接受三种元素参数:
作为 javascript 对象:
var obj = document.querySelector('div#myID > span');
或
var obj = document.getElementById('span#someID');
作为 jquery 对象:
var obj = $('div#myID > span');
或仅作为选择器:
var obj = 'div#myID > span';
用法很简单isfixed(obj);
,并提供布尔值true
或false
最后是混合解决方案(纯 javascript 作为 jquery 插件)
$.fn.isfixed = function(){
var el = this[0];
while (typeof el === 'object' && el.nodeName.toLowerCase() !== 'body') {
if (window.getComputedStyle(el).getPropertyValue('position').toLowerCase() === 'fixed') return true;
el = el.parentElement;
}
return false;
};
用法:$('div#myID > span').isfixed()
如上例所示。
希望你会喜欢它。