-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZhiHuEasyCollapse.user.js
85 lines (76 loc) · 2.66 KB
/
ZhiHuEasyCollapse.user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// ==UserScript==
// @name Zhihu Easy Collapse
// @description 快捷地收起知乎首页的长答案
// @author wenLiangcan
// @version 0.3
// @namespace https://github.com/wenLiangcan
// @homepage https://github.com/wenLiangcan/Userscripts
// @license GPL version 3
// @copyright Copyright © 2015 wenLiangcan
// @updateURL
// @downloadURL
// @match http://www.zhihu.com/*
// @grant none
// @run-at document-end
// ==/UserScript==
(function() {
function getLastItem(arr) {
return arr[arr.length - 1];
}
function toArray(obj) {
return Array.prototype.slice.call(obj);
}
function addFloatingCollapseButtons(feeds) {
feeds.forEach(function(feed) {
var collapseButton = getLastItem(feed.getElementsByClassName('collapse'));
if (collapseButton !== undefined) {
var newButton = collapseButton.cloneNode(true);
newButton.onclick = function() {
feed.scrollIntoView(true);
collapseButton.click();
};
newButton.style.position = 'relative';
newButton.style.marginTop = '1px';
newButton.style.marginLeft = '0px';
try {
var votebar = getLastItem(feed.getElementsByClassName('zm-votebar'));
votebar.appendChild(newButton);
} catch (e) {
console.log(e);
}
}
});
}
function getSelectorsBasedOnUrl() {
var selectors = [];
// explore
if (/^http:\/\/www\.zhihu\.com\/explore(\/(#.*?)?)?$/.test(document.URL)) {
selectors = [
'#js-explore-tab > div:nth-child(4) > div',
'#js-explore-tab > div:nth-child(5) > div'
];
}
// main
else if (/^http:\/\/www\.zhihu\.com(\/(#.*?)?)?$/.test(document.URL)) {
selectors = ['#js-home-feed-list'];
}
return selectors;
}
function observeFeedList(feedList) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
addFloatingCollapseButtons(toArray(mutation.addedNodes));
});
});
var observerConfig = {
childList: true
};
observer.observe(feedList, observerConfig);
}
getSelectorsBasedOnUrl().forEach(function(selector) {
var feedList = document.querySelector(selector);
observeFeedList(feedList);
});
addFloatingCollapseButtons(
toArray(document.getElementsByClassName('feed-item')));
})();