zoukankan      html  css  js  c++  java
  • 取得图片原来的大小

    如果是在预加载的情况下,即没有把图片插入DOM树,它没有受到CSS规则的影响,直接取其img.width与img.height就行了。可以参考〈a href="http://www.cnblogs.com/rt0d/archive/2011/04/17/2018646.html"〉这一篇博文,做得相当棒了。

          function loadImage(url, callback) {
              var img = new Image(); 
              img.onload = function(){
                img.onload = null;
                callback.call(img,img.width,img.height)
              }
              img.src = url; 
            }
    

    但如果在DOM树建完之后,取得某一图片原来的尺寸,在safari,firefox,chrome,与opera10+中,有两个便捷的属性(naturalWidth,naturalHeight)可以做到这一点。

    对于IE与opera的早期版本,就没有这么幸运了,我们需要转换视角,从求当前图片的原来尺寸,变为求另一个同URL的图片的尺寸

         function getActualSize(img){
            var testee = new Image;//弄一个替身
            testee.style.position = 'absolute';
            testee.style.visibility = 'hidden';
            testee.style.top =  testee.style.left = '0px';
            document.body.appendChild(testee);
            testee.src = img.src;
            var width = testee.width;
            var height = testee.height;
            testee.parentNode.removeChild(testee);
            return {width, height:height};
          }
    

    此法虽然因为缓存而不会再发请求,但需要多创建一个元素作为测量对象,开销比较大。有没有更好的办法呢?我们可以考虑一下IE的那三组样式属性了,style,currentStyle与runtimeStyle。眼下,我们只需用到runtimeStyle。它有个特点是,不用同步style就能重绘原来的元素。我们可以直接在runtimeStyle进行设置,然后取得相关值,再重置回去就行了。

          function getActualSize(img) {
            var run = img.runtimeStyle;
            var mem = { w: run.width, h: run.height }; //保存原来的尺寸
            run.width  = run.height = "auto";//重写
            var w = img.width;//取得现在的尺寸
            var h = img.height;
            run.width  = mem.w; //还原
            run.height = mem.h;
            return {w, height:h};
          }
    

  • 相关阅读:
    算法实践--最长公共子序列(Longest Common Subsquence)
    算法实践--最长递增子序列(Longest Increasing Subsquence)
    googletest--Death Test和Exception Test
    googletest--测试控制
    googletest--Test Fixture
    googletest基本测试宏
    使用googletest进行C++单元测试(Netbeans为例)
    Boost--optional
    Boost--any
    Boost--variant (C++中的union)
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/2037115.html
Copyright © 2011-2022 走看看