我在我的投资组合网站上的窗口对象上附加了一个滚动事件(我知道这可能会令人皱眉)。当窗口顶部大于指定的y位置[if(window.top> y)]时,我想向标题元素中添加类以缩小元素的尺寸,并“粘贴”至顶部这页纸。将事件作为参数传递给我的函数时,我必须在不同的浏览器(Chrome = {event.path[1].scrollY
,Safari = event.target.defaultView.scrollY
等)上以不同的方式遍历该事件。我已经编写了检测浏览器的代码,但是,我无法提出一种方法来根据浏览器选择事件的正确路径。
我尝试将数组中的路径保存为字符串,并且根据检测到的浏览器,它将把该字符串作为参数传递。但是,当然这是行不通的。所以这就是我目前所拥有的。
// creates an object called browser to test the behaviors of different browsers.
var Browser = (function () {
"use strict";
var Browser = function () {
this.chrome = function () {
return !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
};
this.firefox = function () {
var iT = window.InstallTrigger;
return typeof iT !== 'undefined';
};
this.explorer = function () {
return !!document.documentMode;
};
this.edge = function () {
return (!!document.documentMode && !!window.StyleMedia);
};
this.safari = function () {
return (/constructor/i).test(window.HTMLElement) || (function (p) {
return p.toString() === "[object SafariRemoteNotification]";
})(!window.safari || (typeof safari !== 'undefined' && safari.pushNotification));
};
};
return Browser;
}());
// Creates the browser object and loops through until true is returned.
function detectBrowser() {
"use strict";
var b = new Browser(),
vendor;
for (vendor in b) {
if (b[vendor] !== 'undefined') {
if (b[vendor]()) {
return vendor;
}
}
}
}
/*-------------------------*/
/* Checks the y position passed in from the event */
function checkPos(e) {
if (e > 50) {
if (logo.classList.length === 0) {
expandHeader();
checkScroll();
}
} else {
if (logo.classList.length === 1) {
minimizeHeader();
}
}
}
/* Adds scroll event and passes the event through to the next function to check it's y position */
function addEvent() {
var browser = detectBrowser();
window.addEventListener("scroll", function (e) {
var event = e;
window.requestAnimationFrame(function () {
checkPos(/* This is where the event will be passed */)
});
});
}
addEvent();