Не удается изменить SRC изображения с Javascript в некоторых версиях Chrome - PullRequest
0 голосов
/ 26 апреля 2011

Никогда бы не подумал, что браузер Chrome мог бы меня расстроить, но слайд-шоу для нашего нового веб-сайта не работает должным образом в некоторых версиях Chrome.

Ошибка возникает здесь:

"mainPicture.src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"

Утверждая, что я не могу изменить mainPicture, идентификатор, который не существует. Очевидно, что другие браузеры не имеют проблем с просмотром этого объекта.

Вся помощь очень ценится!

.

Вы можете найти страницу здесь .

Исходный код:

<?php 
/********************************************************************
 *                GATHER IMAGES FROM IMAGE DIRECTORY                *
 ********************************************************************/

// Define directory where images are stored
$directory = "../../images/slideshow/";

// Create blank array to store image names
$pic_array = array("");
$num_pics;

// Create number to define position of images in array
$counter = 0;

// Gather pictures from image directory
if(is_dir($directory))
{   
    // Open directory to view files
    if($dh = opendir($directory))
    {   
        // Continue while still files to view
        while(($file = readdir($dh)) !== false)
        {   
            // Stop if picture limit of 6 reached
            if($counter == 6)
                break;

            // Gather if object found is file or directory
            $file_check = filetype($directory.$file);

            // If object is a file, add it to the slideshow
            if ($file_check == "file")
            {
                $extension = substr($file, strpos($file, "."));

                if ($extension == ".png" || $extension == ".jpg")
                {
                    $pic_array[$counter] = $file;
                    $counter++;
                }
            }
        }
    }   
}

// Determine number of pics gathered
$num_pics = count($pic_array);
?>

<html>
<head>
<link href="scripts/slideshow.css" rel="stylesheet" type="text/css">

<?php
/********************************************************************
 *                  CONTROL BEHAVIORS OF SLIDESHOW                  *
 ********************************************************************/
?>
<!-- Begin script to control slideshow -->
<script type = "text/javascript">
var thumbTop    = 450; // starting value of thumb.style.top (make sure multiple of increment)
var highestTop  = 342; // highest point mask can be on screen ,-, (make sure multiple of increment)
var lowestTop   = 450; // lowest point mask can be on screen ,_, (make sure multiple of increment)
var delay = 2;      // speed in which slide up and down methods are called
var increment = 5;  // value that thumbTop increments with each method call
var intervalUp;     // interval for thumb upward movements 
var intervalDown;   // interval for thumb downward movements

function startThumbSlideUp()
{
    window.clearInterval(intervalDown);
    intervalUp = window.setInterval(thumbSlideUp,delay);
}

function startThumbSlideDown()
{
    window.clearInterval(intervalUp);
    intervalDown = window.setInterval(thumbSlideDown,delay);
}

function thumbSlideUp()
{
    thumbTop -= increment;

    if (thumbTop <= highestTop)
    {
        thumbTop = highestTop;
        window.clearInterval(intervalUp);
    }
    else
        thumbMask.style.top = thumbTop;
}

function thumbSlideDown()
{
    // Added to fix issue where images would start from too large a height
    if (thumbTop <= highestTop)
        thumbTop = highestTop;

    thumbTop += increment;

    if (thumbTop >= lowestTop)
    {
        thumbTop = lowestTop;
        window.clearInterval(intervalDown);
    }
    else
        thumbMask.style.top = thumbTop;
}

// Move marker above image <pos>
function setMarkerPos(pos)
{
    marker.style.left = 600 - (66 * (pos)) + 19;
}

</script>
</head>

<?php
/********************************************************************
 *                        DISPLAY SLIDESHOW                         *
 ********************************************************************/

// Start body and make images unhighlightable
echo '<body onselectstart="return false" style="margin: 0px;">';

// Create base value to increment horizontal position of thumbnails
$curr_thumb_left = 595; // (ignore this comment) 660<width of image> - 66<width of thumb> - 10<space between side> // 660

// Create and display main (large) image and image thumbnails
echo '<div id="mask" onmouseout = "startThumbSlideDown()" onmouseover = "startThumbSlideUp();">
';
echo '<img src = "'.$directory.$pic_array[0].'" id = "mainPicture" height = "420" width = "660" style = "z-index: -1; position:absolute;"/>
';
echo '<div id="thumbMask" height="66" width="660" style="z-index: 1; top: 450px; position: absolute;">
';
echo '<img id="marker" src="images/marker.png" height="10" width="10" style="z-index: 2; top: 0px; position: absolute;" onload="setMarkerPos(0);"/>';

// Search through image array, then assign names to and display thumbnails
for ($i=0; $i < $num_pics; $i++)
{
    // Point to pic in array
    $current_pic = $pic_array[$i];

    // Create and display image thumbnails
    if ($current_pic !== "")
    {       
        echo '<img src = "'.$directory.$current_pic.'" id = "thumb'.$i.'" height = "50" width = "50" style = "left:'.$curr_thumb_left.'px; top: 10px; border: 3px white solid; position: absolute;" onclick = "mainPicture.src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"/>
        ';

        // Move left value to the left [50px width + (3px padding * 2 sides) + 10px space between = 66px]
        $curr_thumb_left -= 66;
    }
}

echo '</div>';
echo '</div>';
?>

</body>
</html>

Ответы [ 3 ]

1 голос
/ 26 апреля 2011

Вы пытаетесь изменить источник mainPicture, как если бы это была глобальная переменная:

mainPicture.src = '.....';

Попробуйте вместо ссылки mainPicture указать id:

document.getElementById('mainPicture').src = '......';
1 голос
/ 26 апреля 2011

Chrome не делает элементы изображения доступными только по их значению "id";Вы должны использовать document.getElementById("mainPicture"), чтобы получить ссылку на элемент DOM.В любом случае это будет работать во всех браузерах, поэтому можно просто так кодировать.

0 голосов
/ 26 апреля 2011

Вы на самом деле не устанавливаете, что такое mainPicture, другие браузеры должны догадываться, тогда как Chrome делает то, что должен. Изменения:

    echo '<img src = "'.$directory.$current_pic.'" id = "thumb'.$i.'" height = "50" width = "50" style = "left:'.$curr_thumb_left.'px; top: 10px; border: 3px white solid; position: absolute;" onclick = "mainPicture.src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"/>

до

    echo '<img src = "'.$directory.$current_pic.'" id = "thumb'.$i.'" height = "50" width = "50" style = "left:'.$curr_thumb_left.'px; top: 10px; border: 3px white solid; position: absolute;" onclick = "document.getElementById('mainPicture').src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"/>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...