youbbs avatar

减少使用 JavaScript 的 HTML 和 CSS 技术

🕧 by youbbs

现代浏览器的渲染效果,使得可以仅使用 HTML 和 CSS 就能做到以前用 JavaScript 才能做的一些效果。

限制显示的行数

-webkit-line-clamp https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-line-clamp

CSS: -webkit-line-clamp
1
2
3
4
5
6
7
8
9
10
11
/* Keyword value */
-webkit-line-clamp: none;

/* <integer> values */
-webkit-line-clamp: 3;
-webkit-line-clamp: 10;

/* Global values */
-webkit-line-clamp: inherit;
-webkit-line-clamp: initial;
-webkit-line-clamp: unset;

例子

HTML:
1
2
3
4
<p>
  In this example the <code>-webkit-line-clamp</code> property is set to <code>3</code>, which means the text is clamped after three lines.
  An ellipsis will be shown at the point where the text is clamped.
</p>

CSS:
1
2
3
4
5
6
7
p {
  width: 300px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

将元素保留在屏幕上

position: sticky https://developer.mozilla.org/en-US/docs/Web/CSS/position

平滑滚动

scroll-behavior: smooth https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior

CSS: scroll-behavior
1
2
3
4
5
6
7
8
html {
    scroll-behavior: smooth;
}
@media (prefers-reduced-motion: reduce) {
    html {
        scroll-behavior: auto;
    }
}

使用捕捉点滚动

CSS_Scroll_Snap https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Scroll_Snap

CSS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
.diaporama {
    width: 300px;
    overflow-x: auto;
    white-space: nowrap;
    scroll-snap-type: x mandatory;
    display: flex;
}
.smooth-scroll {
    scroll-behavior: smooth;
}

.frame {
    scroll-snap-align: start;
}

图片延迟加载

loading="lazy" https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-loading

💘 相关文章

写一条评论

Based on Golang + fastHTTP + sdb | go1.17.1 Processed in 1ms