1

現在、JS を使用して自分のサイトでローテーション バナーを使用しています。バナーは、ほとんどのバージョンの IE を除くすべてのブラウザーで表示されます。

var banners = Array(); //The first element pushed in the array is at the index 0 

banners.push({link: '', target:'_blank', image: '', title: ''});

var rotate = function() {

//Find all images with class myImage
var images = document.getElementsByClassName('myImage');
var total  = images.length;

//Looping through all the elements found
for (var i = 0; i < total; i++) {
    if (banners.length == 0) {
          break;//No more banners can't display anymore
                }

    //Retrieve a random banner
     var rnd = Math.floor((Math.random()*banners.length));
    //Add the html to the element
    images[i].innerHTML = '<a href="'+banners[rnd].link+'" target="'+banners[rnd].target+'"><img src="'+banners[rnd].image+'" title="'+banners[rnd].title+'" /></a>'; //Added target blank and empty alt attribute
    banners.splice(rnd, 1);
}
}

    if (window.addEventListener)  // W3C DOM
    window.addEventListener('load',rotate,false);
else if (window.attachEvent)  // IE DOM
     window.attachEvent("onload", rotate);

次に、html で単純な div を使用してバナーを呼び出します。

< div class="myImage">< /div>

どんな助けも非常に高く評価されます。

ありがとう、A

4

2 に答える 2

3

getElementsByClassNameIE9でのみ追加されました。IE8をサポートするには、を使用できますが、IE7以下の場合は、属性や。querySelectorAll(".myImage")などの別のものを使用する必要があります。namegetElementsByName

とは言うものの、ページにそのようなバナーが1つしかない場合は、簡単に使用できます。これは<div id="myImage">getElementByIdIEの古いバージョンでも機能します。

于 2013-02-01T01:33:27.507 に答える
0

他の人が言ったようにgetElementsByClassName、ほとんどのバージョンの IE ではサポートされていません。

イベント リスナーに他の IE 固有のコードも使用していることに気付きました。

jQuery などのライブラリが作成されたのは、まさにこのような理由によるものです。必要な機能はすべて jQuery で利用でき、完全にクロスブラウザー互換です。すでに使用しているかどうかはわかりませんが、ここでの問題の解決策として強くお勧めします。それはあなたのコードをよりきれいにします。

jQuery の場合:

$(document).ready(function() {
    var banners = Array(); //The first element pushed in the array is at the index 0 
    banners.push({link: '', target:'_blank', image: '', title: ''});

    //Find all images with class myImage
    $('.myImage').each(function() {
        //Looping through all the elements found
        if (banners.length == 0) {
              return; //No more banners can't display anymore
        }

        //Retrieve a random banner
        var rnd = Math.floor((Math.random()*banners.length));
        //Add the html to the element
        $(this).html('<a href="'+banners[rnd].link+'" target="'+banners[rnd].target+'"><img src="'+banners[rnd].image+'" title="'+banners[rnd].title+'" /></a>'); //Added target blank and empty alt attribute
        banners.splice(rnd, 1);
    }
});

コードよりもはるかに短く、読みやすくなります。もっと短く効率的にすることもできますが、今のところ、既存のコードを jQuery スタイルに変更するだけで済みました。とにかく、それが私の主張を示していることを願っています。

于 2013-02-04T22:11:01.860 に答える