显示基于URL的切换div
我想要一个锚点链接,一旦点击,显示一个div。 我在页面上有一个单击切换工作,但除了该function之外,如果用户点击侧边栏链接,我不希望div切换,我只是希望它显示,如果隐藏。 我已经尝试了几个如果你们等等 – 我认为这是最接近的,但仍然无法正常工作。
函数(首先切换h4,第二个是我尝试在加载URL时显示相同的div …或者单击锚链接):
$(document).ready(function(){ //Hide (Collapse) the toggle containers on load $(".toggle_container3").hide(); //Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state) $(".trigger3").click(function(){ $(this).toggleClass("active").next().slideToggle("slow"); return false; //Prevent the browser jump to the link anchor }).first().click() }); $(function() { if ( document.location.href.indexOf('#papers') > -1 ) { $("#papertoggle").show(); $("h4#papers").addClass("active"); }) });
还试用了这个版本,关键字是“papers”或“climate_change_test#papers”:
// Get URL var url = window.location.href; // Get DIV var msg = document.getElementById('papertoggle'); // Check if URL contains the keyword if( url.search( 'climate_change_test#papers' ) > 0 ) { // Display the message msg.style.display = "block"; }
链接的HTML:
Papers and Publications
h4和div的HTML:
Papers and Publications
content
整个测试页面: http : //www.sea.edu/sea_research/climate_change_test
这应该工作:
$("#over_left a").click(function(){ var id = $(this).attr("href"); $(id).toggleClass("active").next().slideToggle("slow"); });
但是我建议缩小$("#over_left a")
选择器,使其仅适用于那些特定的子菜单链接。
还试用了这个版本,关键字是“papers”或“climate_change_test#papers”:
上面的代码不起作用的原因是因为它是在页面加载时执行的。 但是,当您单击锚标记URL时,页面不会重新加载(它只会跳转到相关的锚点div),因此永远不会执行此代码。
另请注意,您不需要复杂的搜索来查找url中的“ #papers
”部分。 你可以简单地使用:
window.location.hash
在url末尾找到锚点部分。
因此,结合上面的所有信息,您还可以创建一个处理以下示例的函数:如果某人与锚点url共享链接怎么办? 它应该已经自动扩展了,对吧?
// On page load var anchor = window.location.hash; // If there is an anchor in the URL, expand the relevant div if (anchor) { $(anchor).toggleClass("active").next().slideToggle("slow"); }