修订,见下文......
我下降了这里同时为此搜索纯JavaScript解决方案...但我希望有人会喜欢我的jQuery版本。
以下是两个功能,它们的工作方式略有不同,但性能差异很小。我没有测量它,但根据jsperf "each vs filter"的这个测试,.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
UPDATE
而这里的纯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;
};
它接受3种元件参数:
作为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()
如在上面的例子。
希望你会喜欢它。
完美! :D +100 –
很晚,恭喜,但+1 :-),因为我看到你的函数'elementOrParentIsFixed()'几乎和我下面一样,只是我的是一个jQuery插件而不是函数。 – ddlab