2016-11-30 80 views
3

我的网站上有一个脚本,适用于除Internet Explorer之外的每个浏览器。有人可以解释为什么这不起作用吗?我的滚动处理程序JavaScript在Internet Explorer中不起作用

var header = document.getElementById('header'); 
 
var picturebg = document.getElementsByClassName('picturebg')[0]; 
 
var arrow = document.getElementsByClassName('toTop-transparent')[0]; 
 
var supportPageOffset = window.pageXOffset !== undefined; 
 

 
window.onscroll = function() { 
 
    "use strict"; 
 
    var y = window.scrollY; 
 

 
    if (y > 7) { 
 
    header.className = 'header-colored'; 
 
    arrow.className = 'toTop'; 
 
    picturebg.className = 'picturebgns'; 
 
    } else { 
 
    header.className = 'header-transparent'; 
 
    arrow.className = 'toTop-transparent'; 
 
    picturebg.className = 'picturebg'; 
 
    } 
 
};

控制台不给任何错误,它只是不工作。我有另一个运行得很好的jQuery脚本。

我在这里看到了另外一个关于同一事物的问题,但它没有任何帮助。

+0

你用www.caniuse.com检查您正在使用的功能的兼容性如何? – Carcigenicate

+0

那么,这段代码不起作用,因为你没有任何HTML,所以document.getElementById()返回null .... –

+0

如果你已经加载jQuery,为什么不把它移植到jQuery? jQuery的好处之一是其测试方法可以在所有现代浏览器上运行。 – junkfoodjunkie

回答

6

您的摘录中使用的某些属性不受IE的支持。

MDN page on scrollY

对于跨浏览器兼容性,使用window.pageYOffset代替window.scrollY此外,旧版本的Internet Explorer(< 9)不支持任一属性,必须通过检查其他非标准属性来解决。 1

您似乎已经找到了pageOffset支持的检查,所以还检查非标准特性的支持(例如CSS1兼容):

var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"); 

var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop; 

试试这个样本,使用addEventListener()而不是卷轴

var header = document.getElementById('header'); 
 
var picturebg = document.getElementsByClassName('picturebg')[0]; 
 
var arrow = document.getElementsByClassName('toTop-transparent')[0]; 
 
var supportPageOffset = window.pageXOffset !== undefined; 
 
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"); 
 

 

 

 
header.addEventListener('scroll', function(event) { 
 
    "use strict"; 
 
    var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop; 
 
console.log('y: ',y); 
 
    if (y > 7) { 
 
    header.className = 'header-colored'; 
 
    arrow.className = 'toTop'; 
 
    picturebg.className = 'picturebgns'; 
 
    } else { 
 
    header.className = 'header-transparent'; 
 
    arrow.className = 'toTop-transparent'; 
 
    picturebg.className = 'picturebg'; 
 
    } 
 
});
<div id="header" style="height: 50px; overflow: scroll;"> 
 
    <img class="picturebg" src="https://www.gravatar.com/avatar/684fa9ff80577cbde88ffbdebafac5b4?s=32&d=identicon&r=PG&f=1" /> 
 
    <div id="arrow" class="toTop-transparent">&darr;</div> 
 
    </div>


https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY#Notes

+0

window.pageYOffset支持令人惊叹,谢谢! – r4tchet

相关问题