我不知道为什么我的backgroundImage不起作用

时间:2018-08-24 09:41:08

标签: javascript javascript-events

为什么我的横幅不会改变她的背景?请帮助我。

当我运行文件时,控制台会告诉我

Uncaught TypeError: flechedroite.addEventListener is not a function

我真的不明白。我是javascript的初学者,所以请以亲切的方式向我解释如何解决此错误:)

var flechedroite = document.getElementsByClassName('fa-arrow-right');
var flechegauche = document.getElementsByClassName('switch-left');
var banner = document.getElementById('banner');
var images = [];

var changeBackground = function (bElement, bUrl) {
    return bElement.style.backgroundImage = "url(" + bUrl + ")";
}

//image list
images[0] = 'images/image1.jpg';
images[1] = 'images/image2.jpg';
images[2] = 'images/image3.jpg';

flechedroite.addEventListener('click', function() {
    for (var i = 0; i < images.length; i++) {
        changeBackground(document.body, images[i]);
    }
})

3 个答案:

答案 0 :(得分:1)

  1. addEventListener 应该在 window.onload $(document).ready()
  2. 中调用
  3. 由于getElementsByClassName返回一个数组,因此需要将数组索引与flechedroite一起使用以添加事件侦听器。即 flechedroite [0] .addEventListener('click',function(){...});
  4. 您正在循环调用 changeBackground 函数来设置背景图像,实际上,您只会看到数组中最后设置为背景的图像。

JS代码

var  images = [];

var changeBackground = function (bElement, bUrl) {
    return bElement.style.backgroundImage = "url("+bUrl+")";
}

//image list
images[0] = 'https://www.gettyimages.ie/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg';
images[1] = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTOGUhZo0Qe81U5qY_Z-seXgsD79LEEet832TVOlLMOEy10ZPsV';
images[2] = 'https://cdn.pixabay.com/photo/2016/06/18/17/42/image-1465348_960_720.jpg';


window.onload = function(){
    var flechedroite = document.getElementsByClassName('fa-arrow-right');
    var flechegauche = document.getElementsByClassName('switch-left');
    var banner = document.getElementById('banner');
    var currentImageIndex = 0;
    flechedroite[0].addEventListener('click', function() {
        currentImageIndex = (currentImageIndex+1)%images.length;
        changeBackground(document.body, images[currentImageIndex]);
    })
}

答案 1 :(得分:0)

函数getElementsByClassName返回一个HTMLCollection,这是一个类似于数组的结构,可以包含多个元素。因此,您需要使用索引来访问其中包含的元素。

因此flechedroite.addEventListener会导致错误,但flechedroite [0] .addEventListener应该可以工作

https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName

答案 2 :(得分:0)

如果您使用“ getElementsByClassName”并且想要添加“ addEventListener”,则不能以“通用”方式进行操作:"flechedroite.addEventListener ('click', function () {}"。您必须对每个元素执行此操作:

        var flechedroite = document.getElementsByClassName('fa fa-arrow-right');

    //flechedroite  contains all the elements that have the 'fa fa-arrow-right' classes

    //on each element you have to add the "addEventListener"

        for (var i = 0; i < flechedroite.length; i++) {
           flechedroite[i].addEventListener('click', function() {
             alert('flechedroite');
           });
        }

基本示例JSFiddle1

更高级的示例 JSFiddle2