Zhihu Easy Collapse

快捷地收起知乎首页的长答案

目前为 2015-10-23 提交的版本。查看 最新版本

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