使用 URL 哈希在特定选项卡上打开页面
P粉317679342
P粉317679342 2023-09-04 14:33:50
[HTML讨论组]
<p>诚然,我对此有些失落,因为我对哈希很陌生,但我认为这可能是我问题的解决方案,所以我希望这里的人可能有更多的见解。我有一个包含多个“选项卡”的网页(在单击按钮之前隐藏信息的 div,在单击按钮之前隐藏所有其他信息的 div),我希望能够从不同的网页打开到特定选项卡.</p> <p>这是以前网页的骨架。当您定期导航到该页面时,第一个 div 默认可见。</p> <pre class="brush:php;toolbar:false;">&lt;div id=&quot;first&quot; class=&quot;commission&quot;&gt; content &lt;/div&gt; &lt;div id=&quot;second&quot; class=&quot;commission&quot; style=&quot;display:none;&quot;&gt; content &lt;/div&gt; &lt;div id=&quot;third&quot; class=&quot;commission&quot; style=&quot;display:none;&quot;&gt; content &lt;/div&gt;</pre> <p>在此网页上有一些按钮,您可以单击这些按钮在这些 div 之间切换。</p> <pre class="brush:php;toolbar:false;">&lt;button class=&quot;commissiontab&quot; onclick=&quot;commissionType(event, 'first')&quot;&gt;first&lt;/button&gt; &lt;button class=&quot;commissiontab&quot; onclick=&quot;commissionType(event, 'second')&quot;&gt;Second&lt;/button&gt; &lt;button class=&quot;commissiontab&quot; onclick=&quot;commissionType(event, 'third')&quot;&gt;Third&lt;/button&gt;</pre> <p>在这些之间切换的 javascript 如下:</p> <pre class="brush:php;toolbar:false;">function commissionType(evt, commissionName) { var i, commissiontab; var x = document.getElementsByClassName(&quot;commission&quot;); for (i = 0; i &lt; x.length; i++) { x[i].style.display = &quot;none&quot;; } commissiontab = document.getElementsByClassName(&quot;commissiontab&quot;); for (i = 0; i &lt; x.length; i++) { commissiontab[i].className = commissiontab[i].className.replace(&quot; selected&quot;, &quot;&quot;); } window.scrollTo({ top: 0, behavior: 'smooth' }); evt.currentTarget.className += &quot; selected&quot;; document.getElementById(commissionName).style.display = &quot;grid&quot;; }</pre> <p>不知何故,我希望将这些按钮放在不同的页面(“index.html”)上,但是当您单击“第三”时,您将进入新页面(“commissiontypes.html”)选择“第三”而不是默认的“第一”。</p> <p>如果除了使用哈希之外还有其他解决方案,我很想听听,感谢您仔细查看。</p>
P粉317679342
P粉317679342

全部回复(1)
P粉492959599

您最初可以使用 'commission' 类隐藏所有元素,然后在页面加载时根据 location.hash 仅显示其中一个元素。这样,commissiontypes.html(和commissiontypes.html#first)将显示第一个div,commissiontypes.html#second将显示第二个div等

document.querySelectorAll('.commission').forEach(x => x.style.display = 'none');
const activeEl = document.querySelector(location.hash || '#first');
activeEl.style.display = '';

(或者,您也可以考虑使用查询参数来指示该部分。)

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号