php
  • javascript
  • 2012-02-02 67 views 0 likes 
    0

    我有这样的代码:的Javascript调整每个图像加载

    while ($row = mysql_fetch_assoc($result1)) { 
    echo " 
    <a href='#'id='VV".$row['id']."'> 
    <p>".$row['title']."</p> 
    <p>".$row['date']."</p> 
    <img onload='scale()' id='II".$row['id']."' src='../res/videos/img/".$row['img']."'/> 
    </a> 
    <script type='text/javascript'> 
    function scale(){ 
        var image = document.getElementById('II".$row['id']."'); 
        var width = image.width; 
        var height = image.height; 
        if (width > 150) { 
        image.style.width = '150px'; 
        image.style.height = 'auto'; 
        } 
        width = image.width; 
        height = image.height; 
        if (height > 80) { 
        image.style.height = '80px'; 
        image.style.width = 'auto'; 
        } 
        width = image.width; 
        height = image.height; 
    } 
    VV".$row['id'].".onclick = function() { 
    var Result = '".$row['id']."'; 
    location.href='loged.php?Result=' + Result; 
        } 
    </script> 
    "; 
    }?> 
    

    我想调整大小功能加载的每个图像上调用,但最后的图像加载时,它被调用,只有最后一个图像生效。我应该改变什么?

    +0

    在浏览器中你不应该调整图像。浏览器会渲染内容较慢,设计看起来很糟糕。 – machineaddict 2012-02-02 17:36:28

    +0

    我正在缩放它们... – Liukas 2012-02-03 09:08:34

    回答

    1

    我认为你正试图在150x80的区域适合图像。如果是这样的话,我建议你使用CSS background-size: contain来为你做缩放。

    while ($row = mysql_fetch_assoc($result1)) 
        echo "<a href='#' id='VV" . $row['id'] . "'>" . 
          "<p>" . $row['title'] . "</p>" . 
          "<p>" . $row['date'] . "</p>" . 
          "<div id='II" . $row[id] . "' " . 
           "style='width: 150px; " . 
             "height: 80px; " . 
             "background: url(../res/videos/img/" . $row['img'] . "); " . 
             "background-size: contain; " . 
             "background-repeat: no-repeat;'>" . 
          "</div>" . 
         "</a>"; 
    

    将样式抽象为CSS文件是个好主意。

    while ($row = mysql_fetch_assoc($result1)) 
        echo "<a href='#' id='VV" . $row['id'] . "'>" . 
          "<p>" . $row['title'] . "</p>" . 
          "<p>" . $row['date'] . "</p>" . 
          "<div id='II" . $row[id] . "' " . 
           "class='my_img_box' " . 
           "style='background: url(../res/videos/img/" . $row['img'] . ");'>" . 
          "</div>" . 
         "</a>"; 
    

    的CSS

    div.my_img_box { 
        width: 150px; 
        height: 80px; 
        background-size: contain; 
        background-repeat: no-repeat; 
    } 
    
    2

    您正在为每个$行放置脚本。我会有一个javascript函数的副本,然后你可以调用这个函数N次,将id传递给函数。这样,它将适用于所有行,而不仅仅是最后一行(因为JS函数的最后一个副本将是您发现的唯一一个调用的)。

    简短的回答:通过使用一个id参数让你的功能更好,并且只将该功能放在页面上一次。允许您使用每个ID调用该函数。

    相关问题