1

Web サイト用の単純な画像ギャラリー要素を作成しようとしていますが、ばかげた理由でコードに問題があります。私は JavaScript に慣れたことがなく、常に頭の痛い問題でした。他のさまざまな画像ギャラリーを試しましたが、実際に正しく機能させることはできません

私の現在のHTMLコードは次のようなものです:

<!DOCTYPE html>
<html>
    <head>
        <title> Test of slider </title>     
        <script type="text/javascript" src="slider.js"></script>
    </head>
    <body>
        <div class="slider" id="main">
            <img src="#" class="mainImage" />
            <div class="sliderImages" style="display: none;">
                <img src="companion.jpg"/>              
                <img src="cookie.jpg" />
                <img src="orange.jpg" />
                <img src="orangeWhole.jpg" />
            </div>
            <div class="sliderButtons">
                <a href="#" onclick="Slider.Slide('main', -1)"> Previous </a>
                <a href="#" onclick="Slider.Slide('main', 1)"> Next </a>
            </div>
        </div>      
    </body>
</html>

次のようなJavaScriptで:

this.Slider = new function(){
// Stores the indices for each slider on the page, referenced by their ID's
var indices = {};
var limits = {};
var images = {};

// Call this function after a major DOM change/change of page
this.SetUp = function(){        
    // obtain the sliders on the page
    // TODO restrict to those within body
    var sliders = document.getElementsByClassName('slider');
    // assign the indices for each slider to 0
    for(var i = 0; i < sliders.length; i++){
        indices[sliders[i].id] = 0;
        var sliderImages = document.getElementsByClassName('sliderImages');
        var imagesTemp = sliderImages[0].getElementsByTagName('img');
        images[sliders[i].id] = imagesTemp;
        limits[sliders[i].id] = imagesTemp.length;
    }
}

// advances a certain slider by the given amount (usually 1 or -1)
this.Slide = function(id, additive){
    if(indices && id){
        indices[id] = indices[id] + additive;

        // Check limits
        if(indices[id] < 0){
            indices[id] = limits[id] - 1;
        }
        if(indices[id] >= limits[id]){
            indices[id] = 0;
        }

        // alter img to be the new index
        document.getElementById(id).getElementsByClassName('mainImage')[0].src = images[id][indices[id]].src;
    }
}
}
4

2 に答える 2