在这个简短的教程中,我们将使用 javascript 来模拟这种行为。首先,我们将创建一个内容受限的帖子,用渐变遮盖,然后我们会让订阅用户显示完整的帖子。
这是我们的演示:
1.从页面标记开始
我们将首先使用该article
元素来表示典型的博客文章或报纸文章。我们还将它包装在 a.container
中以设置最大页面宽度。
这是相关的标记:
<div class="container"> <article class="post"> <header> <h1 class="post-title">...</h1> <div class="post-meta">...</div> </header> <div class="post-content">...</div> <div class="actions"> <p>...</p> <div class="links">...</div> </div> </article> </div>
2. 添加css
默认情况下,我们将向元素添加一个not-member
类html
(这里我们使用 CodePen 提供的添加类工具:
这确保了最初只有一小部分帖子对读者可见:
更具体地说,我们将只显示标题、前两段和号召性用语链接。我们通过使用“通用兄弟组合器”来选择第二段 ( )之后的所有内容来做到这一点:p:nth-child(2) ~ *
.not-member
.not-member .post-content p:nth-child(2) ~ * { display: none; } .not-member .actions { display: block; }
接下来,我们将为最后一个可见段落(第二个)添加一些样式。我们将逐渐隐藏其内容并在其顶部添加一个挂锁图标。这些样式将让读者知道访问仅限于整篇文章。
这是此位所需的 CSS:
.not-member .post-content p:nth-child(2) {
position: relative;
}
.not-member .post-content p:nth-child(2)::before,
.not-member .post-content p:nth-child(2)::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
right: 0;
}
.not-member .post-content p:nth-child(2)::before {
background: url(padlock.svg) no-repeat center;
z-index: 1;
height: 24px;
}
.not-member .post-content p:nth-child(2)::after {
background: linear-gradient(rgba(255,255,255,0.18) 18%, rgba(255,255,255,0.36) 36%, rgba(255,255,255,0.54) 54%, rgba(255,255,255,0.72) 72%, rgba(255,255,255,0.9) 90%);
height: 100%;
}
为了完善这些基本的样式规则,我们将为号召性用语部分设置样式:
.not-member .actions { font-weight: bold; text-align: center; margin-top: 2rem; } .not-member .links { display: grid; grid-gap: 1rem; grid-template-columns: 1fr 1fr; margin-top: 1rem; } .not-member .links a { background: firebrick; color: white; padding: 0.5rem 0; transition: background 0.3s; } .not-member .links a:hover { background: #9d1e1e; }
3. 解锁优质内容
出于我们简单演示的目的,我们假设读者每次点击行动号召时都会成为高级会员。
在我们的例子中,此时not-member
该类从html
元素中移除,并且完整的帖子内容变得可见。
下面是负责该功能的 JavaScript 代码:
const links = document.queryselectorAll(".not-member .links a"); for(const link of links) { link.addeventListener("click", e => { e.preventDefault(); document.documentElement.classList.remove("not-member"); }); }
当完整的帖子出现时,无需对第二段进行不同的样式设置,也无需显示最初的号召性用语。所以,让我们把它们全部隐藏起来:
.post-content p:nth-child(2)::before, .post-content p:nth-child(2)::after, .actions { display: none; }
最后,我们可以通过点击帖子内容底部的Unsubscribe/Sign Out链接重新开始订阅/取消订阅过程:
这是所需的 javaScript 代码:
const unsubscribe = document.querySelector(".unsubscribe"); unsubscribe.addEventListener("click", e => { e.preventDefault(); document.documentElement.classList.add("not-member"); });
结论
在这个快速教程中,我们构建了一个简单的演示,其中涵盖了一些对受限内容进行样式设置的想法。大型在线报纸和出版商也使用类似的技术,但您自己可能会发现这种技术的用途。
我们只模拟了订阅,因此要正确实现这一点,您必须在幕后制定注册流程。需要注意的是,我们隐藏的内容只是视觉上隐藏的——页面源仍然包含受限内容。如果您要发布真正敏感的材料,请记住这一点。