2011-10-10 75 views
0

大型编辑 - 我试图尽可能清楚地解释我的问题。Javascript - 操纵动态加载(或自动加载)内容的属性

我的目标:到新加载的图像的高度设置为浏览器的大小相同,如果其高度比浏览器

我可以做到这一点的最佳方式是通过我认为的评论代码。 它目前住在http://syndex.me

的成绩单之下,从可以达到取自http://marckremers.com/syndex/js/jquery.infinitescrollfortumblr.js

//Gets the computed style of the image rather than the specified. 
//This was supplied very kindly by @RobG 
//The problem is that on first load, the height for the image is showing as 0 for the larger images. 
//Once it's cached, the functions shows the correct height. 
//I have no idea how to make this function work on a "on Ready" or "On Loaded"? 

function getComputedStyle(el, styleProperty) { 

if (document && document.defaultView && document.defaultView.getComputedStyle) { 
    var styleObj = document.defaultView.getComputedStyle(el, null); 
    var floatStyle = (typeof document.body.style.cssFloat == 'string')?'cssFloat':'styleFloat'; 

    if (styleProperty == 'float') styleProperty = floatStyle; 
    return styleObj && styleObj[styleProperty]; 
    } 
} 
    function addNextPage(oj) { 
     if (oj.status == 404) { 
      tAP.remainFlg = false; 
      return; 
     } 
     var d = document.createElement("div"); 
     d.innerHTML = oj.responseText; 
     var posts = tAP.gP(d.getElementsByTagName("*")); 
     if (posts.length < 2) { 
      tAP.rF = false; 
      return; 
     } 
     d = document.createElement("div"); 
     d.className = "tumblrAutoPager_page_info"; 
     tAP.pp.appendChild(d); 
     for (var i = 0; i < posts.length; i++) { 
     //Goal: Set newly loaded images via this autopager script for tumblr 
     //  to the height of the browser 
     //  (So... IF the image is taller than the browser 
     //  Make the image as tall as the browser) 
     //  In effect I'm trying to make a dynamic image max-height based on the browser 

     // This is loading the new posts (part of the autopager script, not my code) 
     tAP.pp.appendChild(posts[i]); 

     //Over here I'm trying to reference the newly loaded imgs 
     //BUT this is a horrible way of getting them, apprently. 
     //It gets all the imgs in the entire document. 
     //But it seems to work for my array below, anyhow 
     //I really just need to deal with the new ones loaded in. 
     var myDivs = tAP.pp.getElementsByTagName("img"); 
     } 

     var myHeights = []; 
     for (var n=0, iLen=myDivs.length; n<iLen; n++) { 
    myHeights.push(getComputedStyle(myDivs[n], 'height')); 
    } 

    console.log(myHeights) 
    //= I get an array of image heights, however the newly loaded imgs often show up as 0 
    // so the "getcomputedstyle" script is not working as it should yet. 
    //once the page is cached, it works as it should 
     //you can see the console logs here http://syndex.me 

    //Over here would go: 
    //"for each image 
    // if my height is taller then the window 
    // make me as tall as the window" 

    //Finally, I have this working PERFECTLY in the jquery code 
    //you can see it at http://syndex.me on the first page load. 
    //since you can't bind .live or .delegate to events that don't "bubble" 
    //up the DOM tree, i.e. ".load", I can't get it to recognise 
    //newly loaded images from this script 
    //thats why i'm having to hack this file 

     var footer = $("footer"); 
     footer ? footer.parentNode.appendChild(footer) : null; 
     tAP.rF = true; 
    } 

在此先感谢完整的JS文件。

+0

不找好... http://reference.sitepoint.com/javascript/Element/getAttribute –

+0

大,没问题...我真正需要的是刚刚拿到宽度这些divs并能够操纵它们。 – RGBK

+0

如果可以,请使用jQuery,YUI,MooTools,Prototype,Dojo,Scriptaculous等... –

回答

1

可能是因为myDivs包含一个NodeList,一个像对象这样的数组,其中包含对匹配元素的索引引用,它没有getAttribute()成员。

相反,下标各个元件(具有或[n]item(n)),其将具有getAttribute()方法。或者只是使用width属性。

+0

谢谢。我只是不知道下标是什么。然而。我会看看谷歌,但任何示例将不胜感激。 – RGBK

+0

@RGBK:我更新了答案。 – alex

+0

更好的使用属性,因为在许多浏览器中,它将是当前值,而属性值可能没有更新(如果它存在的话)。 – RobG

1

你的代码是错误的:

> myDivs = tAP.pp.getElementsByTagName("img"); 

getElementsByTagName返回现场NodeList

> myWidths = myDivs.getAttribute("width"); 

的NodeLists没有的getAttribute方法,DOM elements做。

在任何情况下,它是更有效的访问属性,所以:

var myWidths = []; 
for (var i=0, iLen=myDivs.length; i<iLen; i++) { 
    myWidths.push(myDivs[i].width); 
} 

然而,除了图像之外的元素通常只有当它已经被设置为一个属性或特性的宽度属性。您可能在计算出的风格之后,例如

<script type="text/javascript"> 
    function getActualWidth(el, styleProperty) { 

    if (document && document.defaultView && document.defaultView.getComputedStyle) { 
     var styleObj = document.defaultView.getComputedStyle(el, null); 
     var floatStyle = (typeof document.body.style.cssFloat == 'string')?'cssFloat':'styleFloat'; 

     if (styleProperty == 'float') styleProperty = floatStyle; 
     return styleObj && styleObj[styleProperty]; 
    } 
    } 
    </script> 
    <div onclick="alert(getActualWidth(this, 'width'));">div</div> 

这会让你的宽度。要改变宽度,只需将它直接:

element.style.width = '500px'; 
+0

我不是一个深度编码器。我知道像jquery这样的东西,我只需要去$(“。myClass”)。(我不相信你甚至不能以简单的方式遍历DOM树,我已经尝试了所有的功能只是为了得到这些div的宽度,我在错误发生错误后得到了错误。如何才能在不引起NodeLists和异常错误的情况下操作这些div? – RGBK

+0

@RGBK - RobG说的是从.getElementsByTagName ()'将是元素的一个*数组*,而不是*元素*注意方法名中的**元素**这很重要,因为在本地JS中,您需要遍历元素数组在每一个工作,而不是'getElementsByTagName()'本身的结果工作 –

+0

得到它。让我看看我能做些什么。上面编辑的代码实际上给我宽度。它现在打破了autopagerizer,最重要的是没有得到它的错误,我想到后,我想出了如何替换getElementsByTagName与更有用的东西。 – RGBK

1

诚然,我从来不知道计算样式,直到我看到这篇文章,所以很遗憾我真的不能上还有什么一直在这里作评论。 (将在此之后阅读 - 我承诺)。

对于事件委托你是对的,因为你不能将一个jQuery live()(或者等价物)绑定到img加载事件,因为它是一个'简单'事件并且不会冒泡。因此,您必须手动将加载事件添加到每个单独的图像。

唯一真正棘手的部分是确保你占已经缓存的图像。这里是one approach

我重新创建了一个简化的静态版本的tumblr页面,其中包含一个追加另一个图像的按钮,它基本上是您的addNextPage()调用。希望能帮助到你。

http://dl.dropbox.com/u/15924676/syndex/index.html

<!DOCTYPE html> 
<html> 
<head> 
    <title>Syndex</title> 
    <script type="text/javascript" src="./Syndex_files/jquery-latest.min.js"></script> 
    <link rel="stylesheet" type="text/css" href="./Syndex_files/style.css" media="screen"> 
</head> 
<body> 
<div> 
    <input type="button" value="add image" /> 
</div> 
<div id="posts"> 
    <div class="autopagerize_page_element"> 
    </div> 
</div> 
</body> 
<script> 

    var $window = $(window); 
    var $pageImages; 
    var images = [ 
     '<div id="10823012653" rel="http://www.tumblr.com/reblog/10823012653/ymaZUCKg" class="post photo"><div class="theImage"><img src="./Syndex_files/tumblr_lsb37adUwD1r4306n" alt="Olaf Breuning"><div class="kremers">original height 701</div></div></div>', 
     '<div id="10822915844" rel="http://www.tumblr.com/reblog/10822915844/JknV8s3a" class="post photo"><div class="theImage"><img src="./Syndex_files/tumblr_lsb33m4S7j1r4306no1_400.png" alt="Jacqueline Casey, Graphic Designer for MIT 1963 - 1990"><div class="kremers">original height 500</div></div></div>', 
     '<div id="10822870581" rel="http://www.tumblr.com/reblog/10822870581/oJMKWl9k" class="post photo"><div class="theImage"><img src="./Syndex_files/tumblr_lsb31sUYvQ1r4306n" alt="Vanessa Veasley x Supreme x Terry Richardson"><div class="kremers">original height 1280</div></div></div>', 
     '<div id="10822380405" rel="http://www.tumblr.com/reblog/10822380405/AwsPNE5L" class="post photo"><div class="theImage"><img src="./Syndex_files/tumblr_lsb2ivLTWQ1r4306n" alt="Xavier Delory - Habitat"><div class="kremers">original height 857</div></div></div>', 
     '<div id="10822233573" rel="http://www.tumblr.com/reblog/10822233573/9OTI6gLl" class="post photo"><div class="theImage"><img src="./Syndex_files/tumblr_lsb2d6sESW1r4306n" alt="Yellow Smoke Bomb"><div class="kremers">original height 900</div></div></div>', 
     '<div id="10822153538" rel="http://www.tumblr.com/reblog/10822153538/GhQQOncG" class="post photo"><div class="theImage"><img src="./Syndex_files/tumblr_lsb2a3Gh2L1r4306n" alt="Karl Gerstner - Colour Sounds"><div class="kremers">original height 1024</div></div></div>', 
     '<div id="10822119380" rel="http://www.tumblr.com/reblog/10822119380/mTyZ3yoh" class="post photo"><div class="theImage"><img src="./Syndex_files/tumblr_lsb28q4g7p1r4306n" alt="Karl Gerstner - Colour Sounds"><div class="kremers">original height 1024</div></div></div>', 
     '<div id="10822031937" rel="http://www.tumblr.com/reblog/10822031937/OoqboZsY" class="post photo"><div class="theImage"><img src="./Syndex_files/tumblr_lsb258iApO1r4306n" alt="Cindy Sherman - Untitled Film Still #45"><div class="kremers">original height 920</div></div></div>', 
     '<div id="10821751285" rel="http://www.tumblr.com/reblog/10821751285/LlXg7AsU" class="post photo"><div class="theImage"><img src="./Syndex_files/tumblr_lsb1u2045A1r4306n" alt="Jeff Koons - Rabbit (1986)"><div class="kremers">original height 1280</div></div></div>', 
     '<div id="10821655695" rel="http://www.tumblr.com/reblog/10821655695/RBKyq24s" class="post photo"><div class="theImage"><img src="./Syndex_files/tumblr_lsb1q8whpQ1r4306n" alt="Disabled Car Access"><div class="kremers">original height 757</div>/div></div>', 
     '<div id="10821572995" rel="http://www.tumblr.com/reblog/10821572995/JYWoYWR6" class="post photo"><div class="theImage"><img src="./Syndex_files/tumblr_lsb1mw5IU11r4306n" alt="Bin Bags"><div class="kremers">original height 725</div></div></div>', 
     '<div id="10821503505" rel="http://www.tumblr.com/reblog/10821503505/hVLYhypW" class="post photo"><div class="theImage"><img src="./Syndex_files/tumblr_lsb1k3yEsf1r4306no1_400.png" alt="Untitled"><div class="kremers">original height 326</div></div></div>' 
    ]; 

    $(document).ready(function() { 

     $('input').click(function(e){ 
      e.preventDefault(); 

      if (images.length > 0) { 
       // append first image in array to DOM 
       $(images[0]) 
        .appendTo('.autopagerize_page_element') 
         // select img elements from appended items 
         .find('img').each(function(e) { 

          // lets hide the description as well while we're at it 
          $(this).parent().find('.kremers').hide(); 

          // hide image from the DOM 
          $(this).hide(); 

          // check to see if our image has been cached 
          // source: https://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached 

          $(this).one('load', function() { 
           imageLoadHandler($(this)); 
          }).each(function() { 
           if(this.complete) { 
            // (image is cached) 
//         console.log("cached"); 
            $(this).load(); 
           } 
          }); 
         } 
       ); 

       // remove first element from array 
       images.shift(); 

       // update our reference to all nested images 
       $pageImages = $('.autopagerize_page_element img'); 
      } else { 
       // disable input (jQuery 1.6+) 
       $(this).prop('disabled', true); 
      } 
     }); 

     $(window).resize(function(e){ 
      // TODO: look into throttling these calls as it doesn't need to be called so often 
      // potentially with the use of something like jQuery throttle/debounce 
      // http://benalman.com/projects/jquery-throttle-debounce-plugin/ 

      // add your resize code here 
      $pageImages.each(function(){ 
       // resize all images to browser height 
       $(this).height($window.height()); 
      }); 
     }); 
    }); 

    function imageLoadHandler($img){ 
     // resize to browser window height, even images that are initially smaller than browser window height 
     $img.height($window.height()); 

     /* 
     // OR... 

     // check if this image is taller than our browser window 
     if ($img.height() > $window.height()) { 
      // resize to browser window height 
      $img.height($window.height()); 
     } else { 
      // our image is smaller than the browser height, we don't need to do anything 
     } 
     */ 

     // reveal the image in the DOM 
     // (fade in, animate in, do whatever else you want here) 
     $img.show(); 

     // finally show our description again 
     $img.parent().find('.kremers').show(); 
    } 

</script> 
</html> 
+0

哇,这是超棒的罗宾。我明天要去咀嚼。我并不期待jquery解决方案,对此非常满意。尽快回复你!这周我们来喝一杯啤酒吧。 – RGBK