【问题标题】:JavaScript not working in IE 6/7 for my websiteJavaScript 在我的网站的 IE 6/7 中不起作用
【发布时间】:2017-04-02 04:25:34
【问题描述】:

我的网站上运行了一些代码,该代码将检测 ID 为 photodiv 是否显示在屏幕上或滚动到屏幕上。如果显示div,则会将class 添加到div,这将导致背景图像加载到div 中。目的是延迟加载图像,以便网站加载更快。

它在除 IE 6/7 之外的所有浏览器中都运行良好。谁能告诉我下面的代码有什么问题阻止它在这些 IE 浏览器中工作?

function $(a){
    return document.getElementById(a)
}
function scrll(){
    function a(d){
        var f=d.offsetTop,
            e=d.offsetLeft,
            c=d.offsetWidth,
            b=d.offsetHeight;
        while(d.offsetParent){
            d=d.offsetParent;
            f+=d.offsetTop;
            e+=d.offsetLeft
        }
        return(f<(window.pageYOffset+window.innerHeight)
            &&e<(window.pageXOffset+window.innerWidth)
            &&(f+b)>window.pageYOffset&&(e+c)>window.pageXOffset)
    }
    if(a($("photo"))){
        $("imgholder").className="pic11 pic21";
        if(window.removeEventListener){
            window.removeEventListener("scroll",scrll,false)
        }else{
            if(window.detachEvent){
                window.detachEvent("onscroll",scrll)
            }else{
                window.onscroll=null
            }
        }
    }
}
if(window.addEventListener){
    window.addEventListener("scroll",scrll,false);
}else{
    if(window.attachEvent){
        window.attachEvent("onscroll",scrll);
    }else{
        window.onscroll=scrll;
    }
}
setTimeout(scrll,1);

代码在我的网站上有效:http://www.ericperrets.info/

【问题讨论】:

  • 哪一部分不起作用?您可以输入一些console.log()alert() 语句来查看您的代码是否正在运行? (另外,你不能通过将$("imgholder").className="pic11 pic21"; 部分放在 onload 处理程序中来实现类似的效果,这样在页面的其余部分完成加载之前不会设置图像吗?)
  • 在我的情况下,onload 处理程序并不理想,因为我的网站针对移动设备进行了优化,我不想使用资源来加载图像,除非有人真的向下滚动查看照片部分。
  • 我还要提一下,我是在 Mac 上开发的,所以我无法访问 Internet Explorer 来调试代码(添加 alert/console.log 调用)。
  • @Eric 你可以从微软免费获取包含 IE 的 VirtualBox 和 Windows 开发镜像。

标签: javascript internet-explorer-7 internet-explorer-6 lazy-loading onscroll


【解决方案1】:

IE 没有innerHeight。改用这个函数:

function getWindowHeight()
{
    if (window.innerHeight) return window.innerHeight;
    if (window.document.documentElement.clientHeight) return window.document.documentElement.clientHeight;
    return window.document.body.clientHeight;
}

另外,一篇解释浏览器之间差异的好文章位于http://www.howtocreate.co.uk/tutorials/javascript/browserwindow

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多