Zhihu Easy Collapse

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

当前为 2015-09-20 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Zhihu Easy Collapse
  3. // @description 快捷地收起知乎首页的长答案
  4. // @author wenLiangcan
  5. // @version 0.1
  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. // @require http://cdn.staticfile.org/jquery/2.1.1-rc2/jquery.min.js
  13. // @include http://www.zhihu.com/
  14. // @include http://www.zhihu.com/explore
  15. // @run-at document-end
  16. // @grant GM_log
  17. // ==/UserScript==
  18.  
  19. (function() {
  20. function main() {
  21. function addFloatingCollapseButtons(feeds) {
  22. feeds.forEach(function(feed) {
  23. var collapseButton = feed.find('.collapse').eq(0);
  24. var newButton = collapseButton.clone()
  25. .on('click', function() {
  26. $('html body').animate({
  27. scrollTop: feed.offset().top - 50
  28. }, 300, function() {
  29. collapseButton.trigger('click');
  30. });
  31. })
  32. .css({
  33. position: "relative",
  34. marginTop: "1px",
  35. marginLeft: "0px"
  36. });
  37. try {
  38. feed.find('.zm-votebar').append(newButton);
  39. } catch (e) {
  40. GM_log(e);
  41. }
  42. });
  43. }
  44.  
  45. function getSelectorsBasedOnUrl() {
  46. if (/^http:\/\/www\.zhihu\.com\/explore.*?$/.test(document.URL)) {
  47. return [
  48. '#js-explore-tab > div:nth-child(4) > div',
  49. '#js-explore-tab > div:nth-child(5) > div'
  50. ];
  51. } else {
  52. return ['#js-home-feed-list'];
  53. }
  54. }
  55.  
  56. function observeFeedList(feedList) {
  57. var observer = new MutationObserver(function(mutations) {
  58. mutations.forEach(function(mutation) {
  59. addFloatingCollapseButtons($.makeArray(mutation.addedNodes).map($));
  60. });
  61. });
  62. var observerConfig = {
  63. childList: true
  64. };
  65. observer.observe(feedList, observerConfig);
  66. }
  67.  
  68. getSelectorsBasedOnUrl().forEach(function(selector) {
  69. var feedList = document.querySelector(selector);
  70. observeFeedList(feedList);
  71. });
  72.  
  73. addFloatingCollapseButtons((function() {
  74. var feeds = [];
  75. var feedList = $('.feed-item');
  76. for (var i = 0; i < feedList.length; i++) {
  77. feeds.push(feedList.eq(i));
  78. }
  79. return feeds;
  80. })());
  81. }
  82.  
  83. // http://skratchdot.com/2013/05/userscripts-and-content-security-policy/
  84. var injectViaIframe = function(fn) {
  85. var fnName = 'dynamic_fn_' + (new Date()).getTime(),
  86. iframe = document.createElement('iframe');
  87. iframe.onload = function() {
  88. parent.window[fnName] = new Function('(' + fn.toString() + '());');
  89. parent.window[fnName]();
  90. parent.document.body.removeChild(iframe);
  91. };
  92. document.body.appendChild(iframe);
  93. };
  94.  
  95. injectViaIframe(main);
  96. })();