我正在努力将我的代码转换为纯 JS,这真的很难。我需要一个函数来获取真正的滚动容器,我的滚动容器是这样的,使用 .map()
。
//get true container for scroll events
function getScrollContainer(c) {
return $(c).map(function() {
var cnt = this,
isWin = !cnt.nodeName || $.inArray( cnt.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;
if (!isWin) return cnt;
var doc = (cnt.contentWindow || cnt).document || cnt.ownerDocument || cnt;
return /webkit/i.test(navigator.userAgent) || doc.compatMode == 'BackCompat' ?
doc.body :
doc.documentElement;
});
}
console.log(getScrollContainer(window));
有办法做到这一点吗?
最佳答案
Map 只是一种奇特的方式来表示“将此函数应用于列表中的每个元素”,因此可以在 for 循环中轻松实现它。
像这样的东西:(不完美或经过测试,但应该给你一个想法)
function getScrollContainer(c) {
c = Object.prototype.toString.call( c ) === '[object Array] ? c : [c];
for (var i = 0; i < c.length; i++) {
var cnt = c[i],
isWin = !cnt.nodeName || indexOf(cnt.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;
if (!isWin) return cnt;
var doc = (cnt.contentWindow || cnt).document || cnt.ownerDocument || cnt;
return /webkit/i.test(navigator.userAgent) || doc.compatMode == 'BackCompat' ?
doc.body :
doc.documentElement;
}
}
关于javascript - 如何在普通 JS 中实现 jQuery .map() 的等效项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28794296/