Skip to content

Commit 1e2fb15

Browse files
committed
Fix the compatibility of the smooth scrolling in Safari
Safari(at least on v14) does not support CSS property `scroll-behavior`
1 parent 73658c1 commit 1e2fb15

File tree

5 files changed

+50
-2
lines changed

5 files changed

+50
-2
lines changed

assets/css/_addon/main.scss

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@ html[mode=dark] {
4848

4949
:root {
5050
font-size: 16px;
51-
scroll-behavior: smooth;
5251
}
5352

5453
body {

assets/js/_commons/back-to-top.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ $(function() {
1212
});
1313

1414
$("#back-to-top").click(() => {
15-
$("body,html").scrollTop(0);
15+
$("body,html").animate({
16+
scrollTop: 0
17+
}, 800);
1618
return false;
1719
});
1820
});

assets/js/_utils/smooth-scroll.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
Safari doesn't support CSS `scroll-behavior: smooth`,
3+
so here is a compatible sollution for all browser to smooth scrolling
4+
5+
See: <https://css-tricks.com/snippets/jquery/smooth-scrolling/>
6+
7+
Warning: It must be called after all `<a>` tags (e.g., the dynamic TOC) are ready.
8+
*/
9+
10+
$(function() {
11+
$("a[href*='#']")
12+
.not("[href='#']")
13+
.not("[href='#0']")
14+
.click(function(event) {
15+
16+
if (location.pathname.replace(/^\//, "") === this.pathname.replace(/^\//, "")
17+
&& location.hostname === this.hostname) {
18+
19+
var target = $(decodeURI(this.hash));
20+
21+
if (target.length) {
22+
23+
event.preventDefault();
24+
25+
$("html, body").animate({
26+
scrollTop: target.offset().top
27+
}, 800, function() {
28+
var $target = $(target);
29+
$target.focus();
30+
31+
if ($target.is(":focus")) { /* Checking if the target was focused */
32+
return false;
33+
} else {
34+
$target.attr("tabindex", "-1"); /* Adding tabindex for elements not focusable */
35+
$target.focus(); /* Set focus again */
36+
}
37+
});
38+
}
39+
}
40+
41+
}); /* click() */
42+
});

assets/js/page.min.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@ layout: compress
99
---
1010

1111
{% include_relative _commons.js %}
12+
13+
{% include_relative _utils/smooth-scroll.js %}

assets/js/post.min.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,6 @@ layout: compress
1717
{% include_relative _utils/img-hyperlink.js %}
1818

1919
{% include_relative _utils/lang-badge.js %}
20+
21+
{% comment %} `smooth-scroll.js` must be called after ToC is ready {% endcomment %}
22+
{% include_relative _utils/smooth-scroll.js %}

0 commit comments

Comments
 (0)