Pixiv Image Size Fitting

pixiv の原寸画像が表示領域に収まるように画像サイズを変更

От 08.10.2014. Виж последната версия.

// ==UserScript==
// @name        Pixiv Image Size Fitting
// @namespace   http://userscripts.org/users/121129
// @description pixiv の原寸画像が表示領域に収まるように画像サイズを変更
// @include     http://www.pixiv.net/member_illust.php?*
// @version     7
// @grant       none
// @license     MIT
// ==/UserScript==

;(function() {
  'use strict'

  var img = document.querySelector('img')

  function hasBigModeParam() {
    return window.location.search.slice(1).split('&').indexOf('mode=big') >= 0
  }
  function fitImageIfLargerThanWindow() {
    if (img.height > window.innerHeight) img.height = window.innerHeight
    if (img.width > window.innerWidth) {
      if (img.hasAttribute('height')) {
        img.height = Math.round(img.height * (window.innerWidth / img.width))
      }
      img.width = window.innerWidth
    }
  }
  function isCharKeyEvent(event, chars) {
    return !event.altKey
        && !event.ctrlKey
        && !event.metaKey
        && !event.shiftKey
        && chars.indexOf(String.fromCharCode(event.keyCode).toLowerCase()) >= 0
  }
  function isFitted() {
    return img.hasAttribute('height') || img.hasAttribute('width')
  }
  function clearFitting() {
    img.removeAttribute('height')
    img.removeAttribute('width')
  }
  function toggleImageSize() {
    if (isFitted()) {
      clearFitting()
    } else {
      fitImageIfLargerThanWindow()
    }
  }
  function main() {
    if (!hasBigModeParam()) return
    if (img.complete) {
      fitImageIfLargerThanWindow()
    } else {
      img.addEventListener('load', fitImageIfLargerThanWindow)
    }
    window.addEventListener('resize', function() {
      if (!img.complete) return
      if (isFitted()) clearFitting()
      fitImageIfLargerThanWindow()
    })
    window.addEventListener('keydown', function(e) {
      if (isCharKeyEvent(e, ['o', 'v'])) toggleImageSize()
    })
  }

  main()
})()