【问题标题】:Loading an event on url change在 url 更改时加载事件
【发布时间】:2018-06-13 13:04:23
【问题描述】:

如何使页面加载到某个部分并打开手风琴。

例如,我有一个页面,其中垂直列出了一堆手风琴,是的,我知道为它们提供 id 的选项,并且在 url page#accordion1 中将打开它并准确滚动到那里。那么,我在这里缺少什么样的 JS,以便在某些 url 路径上自动加载 #accordion1 加载?

【问题讨论】:

  • 如果您发布了代码会更容易。
  • 您找到想要的答案了吗?
  • 是的,代码如下...

标签: javascript jquery html url accordion


【解决方案1】:

我们首先需要等到整个页面加载完毕,以防您的手风琴尚未完全初始化。

然后我们从 URL 中获取哈希值,以便检查它是否与我们想要的匹配。此外,我们使用 switch 语句来检查已知值,因为我们不能信任任何输入。

我们通过 ID 找到相关的手风琴,如果您的代码没有,则需要添加。

// Trigger when the whole document loads
window.onload = function(){
    // Grab the hash out of the URL
    switch(window.location.hash){
        case "#accordion1":
            // Click the relevant item located by its ID
            document.getElementById("accordion1ID").click();
            break;
        case "#accordion2":
            document.getElementById("accordion2ID").click();
            break;
    }
}

【讨论】:

    【解决方案2】:

    所以,这行得通……所以如果 url 以任何具有 id 的元素为目标,它会滚动到它并执行操作。在这种情况下,它将打开手风琴(添加和删除一个类)

    (function($){
    $(window).load(function(){
    var et_hash = window.location.hash;
    if(window.location.hash) {
    $( '.et_pb_toggle' + et_hash )
    .removeClass('et_pb_toggle_close')
    .addClass('et_pb_toggle_open')
    }
    });
    })(jQuery)
    
    document.addEventListener('DOMContentLoaded', function(event){ 
    
        if (window.location.hash) {
            // Start at top of page
            window.scrollTo(0, 0);
    
            // Prevent default scroll to anchor by hiding the target element
            var db_hash_elem = document.getElementById(window.location.hash.substring(1));
            window.db_location_hash_style = db_hash_elem.style.display;
            db_hash_elem.style.display = 'none';
    
            // After a short delay, display the element and scroll to it
            jQuery(function($){
                setTimeout(function(){
                    $(window.location.hash).css('display', window.db_location_hash_style);
                    et_pb_smooth_scroll($(window.location.hash), false, 800);
                }, 700);
            });     
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 2013-12-16
      相关资源
      最近更新 更多