我如何在使用fullpage.js时改变基于URL哈希的图像

How can I change an image based on URL hash when using fullpage.js?

本文关键字:改变 URL 哈希 图像 js fullpage      更新时间:2023-09-26

我目前正在使用fullPage.js为我正在创建的网站。请注意,当您滚动时,它如何向URL添加一个哈希值(即。#feature1)。我想根据哈希值

更改图像或背景图像

这是我的<body>标签上面初始化fullPage.js

    $(document).ready(function() {
        $('#fullpage').fullpage({
            anchors: ['welcome', 'feature1', 'feature2', 'feature3', 'feature4', 'feature5', 'feature6'],
            sectionsColor: ['transparent', '#1BBC9B', '#7E8F7C', '#C63D0F', '#1BBC9B', '#7E8F7C'],
            navigation: true,
            navigationPosition: 'left',
        });
    });

我正在使用这个javascript来尝试改变图像,虽然我很确定document.write是错误的。

    $(document).ready(function() {
      // Which anchor is being used?
      switch(window.location.hash) {
         case "#feature1":
           document.write('<img class="screen" src="img/bg-feature-2.jpg">');
         break;
         case "#feature2":
           document.write('<img class="screen" src="img/bg-feature-1.jpg">');
         break;
      }
    });

如果我滚动到#feature1或#feature2,它什么也不做。但是,如果我直接在浏览器中键入带有哈希值的URL,它将只显示图像而不显示其他内容。我该如何解决这个问题?

正如@Brian Ray指出的那样,你应该使用fullpage.js回调。

您可以使用afterLoadonLeave的部分和afterSlideLoadonSlideLoad的幻灯片。

例如:

$('#fullpage').fullpage({
    anchors: ['firstPage', 'secondPage', 'thirdPage', 'fourthPage', 'lastPage'],
    afterLoad: function (anchorLink, index) {
        var loadedSection = $(this);
        //using anchorLink
        if (anchorLink == 'secondSlide') {
            alert("Section 2 ended loading");
        }
    }
});

虽然在你的情况下,我会直接在CSS中使用fullpage.js添加到body元素的fp-viewing-section-slide类型的CSS类。

看看这个视频教程,它解释了如何使用它。

例如:

body.fp-viewing-firstPage #myImage{
    background: url('demo.gif');
}
body.fp-viewing-secondPage #myImage{
    background: url('otherImage.gif');
}

您需要将您的页面绑定到hashchange事件:

$(function(){
  // Bind an event to window.onhashchange that, when the hash changes, gets the
  // hash and adds the class "selected" to any matching nav link.
  $(window).hashchange( function(){
    var hash = location.hash;
    // Change the image link using the following code:
    // $(".screen").attr("src", "img/bg-feature-2.jpg");
    switch(window.location.hash) {
      case "#feature1":
        $(".screen").attr("src", "img/bg-feature-2.jpg");
        break;
      case "#feature2":
        $(".screen").attr("src", "img/bg-feature-1.jpg");
        break;
    }
  })
  // Since the event is only triggered when the hash changes, we need to trigger
  // the event now, to handle the hash the page may have loaded with.
  $(window).hashchange();
});

我使用The hash is blank作为引用

您正在寻找hashchange事件- Mozilla有相关文档。

但是基本上可以这样使用:

window.addEventListener("hashchange", function() {
  // called whenever the hash changes
  // put your switch / case here.
}, false);

您的$(document).ready()方法的问题是,它只在页面加载后运行一次(实际上,一旦文档准备好)。而不是以后。url哈希值的变化并不是加载什么东西,它只是将您跳转到同一文档的不同"片段"。