繁体   English   中英

内联JavaScript似乎随机加载(如果有的话)

[英]Inline JavaScript seems to load randomly, if at all

首先,如果这是一个简单的问题,我想对不起。 我对HTML / CSS领域还很陌生,甚至还没有使用Javascript。

这是我的问题。 我有一个网站正在为叔叔建立,您可以在此处查看 (尚处于Alpha之前的阶段,因此链接无法正常工作)。 它可以作为本地文件正常工作,但是一旦托管了它,我的“ sticky”标头就开始粘得太早(如果有的话)。 重新载入页面的工作量大约为10分之一。

我可能会或可能没有发现问题的原因:我的占位符。 我的粘性代码本身在大多数情况下都能正常工作,除了以下几点:粘性条停靠时,它变得固定了,文本跳了90多个像素。 为了解决这个问题,我在下面的代码中添加了第6行和第7行:

var sticky = document.querySelector('.sticky');
var origOffsetY = sticky.offsetTop;
function onScroll(e) {
window.scrollY >= origOffsetY ? sticky.classList.add('fixed') :
  sticky.classList.remove('fixed');               
window.scrollY >= origOffsetY ? jQuery('.content').css("paddingTop", "88.8125px"):
  jQuery('.content').css("paddingTop", "0px");
}
document.addEventListener('scroll', onScroll);

基本上,它会在其中保留一个占位符以阻止该跳转。 它工作正常,除非现在它破坏了我的代码。 我做了一些实验,发现占位符似乎是随机加载的,而标题却变得很奇怪。 那是我所能做的最好的。

似乎是占位符代码破坏了它,因为如果没有代码,它似乎可以正常工作,也许是在几次重载之后。 但是,我完全陷入了困境。 有谁知道如何解决它?

(虽然在另一个级别上有问题,但已在64位和32位Chrome浏览器以及Android版Chrome上进行了测试。尽管在另一个级别上也有问题。可以在本地页面上正常使用,但在托管时不能使用。)

似乎这些代码执行得太早,以至于图像尚未加载,您可以使用chrome dev工具添加一个暂停var origOffsetY = sticky.offsetTop;来中断var origOffsetY = sticky.offsetTop;

然后您会看到2种情况: 22642

您可以进一步检查在满足22条件时图像(应该是横幅)没有完成,如果您使用document.querySelector('.splash img')进行获取并检查其高度,则会看到0 642情况下,您将获得500

区别有时可能是图像来自缓存,有时是从Internet加载,因此执行脚本时它可能会或可能无法确定高度。

因此,我们必须确保.splashimage已经加载:

<script>

// Wrap the logic to a function for call.
var stickFunction = function() {
    var sticky = document.querySelector('.sticky');
    var origOffsetY = sticky.offsetTop;

    function onScroll(e) {
      window.scrollY >= origOffsetY ? sticky.classList.add('fixed') :
                                      sticky.classList.remove('fixed');

      window.scrollY >= origOffsetY ? jQuery('.content').css("paddingTop", "88.8125px"):
                                      jQuery('.content').css("paddingTop", "0px");
    }

    document.addEventListener('scroll', onScroll);
}

// Get the image element
var splashImage = document.querySelector('.splash img');

// Check if image is complete or not.
if (splashImage.complete) { // If completed, do the logic.
    stickFunction();
} else { // If not, tell the image to call the function for you when it is loaded.
    splashImage.onload = stickFunction;
}


</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM