首页 > 解决方案 > 如何创建一个打开页面并在其中显示隐藏 div 的链接?

问题描述

我有一个页面,其中有一个隐藏的 div。单击某个按钮后,此 div 将显示在此页面中。是否可以创建一个链接(例如插入电子邮件)来打开该页面并显示隐藏的 div?谢谢

编辑

是否可以同时显示一个 div 并隐藏其他 div?例如:

website.com/page.php#show

这个链接完成了这项工作。同时我可以隐藏其他div吗?

标签: javascripthtmljquery

解决方案


CSS 解决方案

确实。使用 CSS :target 选择器,您可以根据 URL 中的哈希值更改元素的样式。看看下面的例子。它添加#show到使隐藏的 div 可见的 URL。这是因为#show哈希与iddiv 上的属性相匹配。这样它就知道它正在成为目标。

如果您在链接中id添加与页面上 div 的属性值匹配的哈希,并将 CSS 添加到您的样式中,那么您将能够创建此效果。

.hidden {
  display: none;
}

.hidden:target {
  display: block;
}
<a href="#first">Show the first div</a>
<a href="#second">Show the second div</a>
<a href="#third">Show the third div</a>

<div class="hidden" id="first">Excelsior!</div>
<div class="hidden" id="second">Tadaa!</div>
<div class="hidden" id="third">Shazam!</div>


附录:JavaScript 解决方案

更改不相关元素的可见性将需要 JavaScript 的帮助。有了它,我们可以确定任何其他没有被定位的 div 应该从文档中隐藏。我们将通过阅读 URL 来做到这一点。

对象的hash属性location会告诉我们散列是否有值。我们可以将散列的值与我​​们选择的元素的 id 进行比较,以确定是否应该根据散列显示或隐藏它们。

下面的示例选择所有元素class="js-target"并检查id每个元素的值是否匹配hash。如果是,则显示该元素,如果不是,则隐藏该元素。这将导致隐藏所有不匹配的元素。

// Selects all divs with the .js-target class.
const targets = document.querySelectorAll('div.js-target');

/**
 * Show the target that has an id that matches
 * with the hash value in the URL and hides the
 * ones that don't match.
 */
const toggleTargets = () => {
  const { hash } = window.location;
  if (hash === '') {
    return;
  }
  /**
   * Loop over each target and check if the id matches
   * the hash value. If it does, then remove the hidden 
   * class, if not, add the hidden class.
   */
  targets.forEach(target => {
    if (`#${target.id}` === hash) {
      target.classList.remove('hidden');
    } else {
      target.classList.add('hidden');
    }
  });
}

/**
 * Immediately execute the toggleTargets function when
 * the script is loaded.
 */
toggleTargets();

/**
 * Whenever the hash changes when on the page, call toggleTargets
 * again to re-evaluate if the hash matches any div.
 */
window.addEventListener('hashchange', toggleTargets);
.hidden {
  display: none;
}
<a href="#tadaa">Show the targeted div</a>

<div class="js-target">Excelsior!</div>
<div class="js-target hidden" id="tadaa">Tadaa!</div>
<div class="js-target">Shazam!</div>


推荐阅读