修訂,見下文......
我下降了這裏同時爲此搜索純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