изменить изображение после нажатия, но сбросить другие вкладки в исходное изображение JavaScript - PullRequest
0 голосов
/ 13 декабря 2018

У меня есть 3 изображения (машина, поезд, самолет).Когда я нажимаю на каждую из них, div info получает информацию о путешествии.Я хотел бы изменить состояние изображения, как при наведении курсора, каждый раз, когда я нажимаю на изображение.Он делает это, но проблема в том, что когда я нажимаю на новое изображение, старое не возвращается в исходное состояние.Пожалуйста помоги.

<div class="car tab"></div>
<div class="train tab"></div>
<div class="plane tab"></div>
<div class="info" id="info">                        
</div>

.car {
  background: url(../images/car_state.png) no-repeat;
  display: block;
  background-size: 88px 38px;
  height: 38px;
  width: 44px;
}

.car:hover {
  background-position: -44px 0;
}

.train {
  background: url(../images/train_state.png) no-repeat;
  display: block;
  background-size: 70px 53px;
  height: 53px;
  width: 35px;
}

.train:hover {
  background-position: -35px 0;
}


.plane {
  background: url(../images/plane_state.png) no-repeat;
  display: block;
  background-size: 95px 48px;
  height: 48px;
  width: 48px;
}

.plane:hover {
  background-position: -48px 0;
}

.states {
    width: 100%;
    text-align: center;
}

.car, .train, .plain {
    display: inline-block;
}

.train {
    margin: 0 30px;
}

.info {

}

const info = document.getElementById("info");
const tab = document.getElementsByClassName("tab");
let el;
let arr = Array.prototype.slice.call(tab);


const getThere = [
{
    line1: "By train....",
    x:"-44px"
},
{
    line1: "By car....",
    x:"-35px"
},
{
    line1: "By plane....",
    x:"-48px"
}
];

for(let i = 0; i < arr.length; i++) {
   arr[i].addEventListener("click", function() {
    if (arr.indexOf(this) == getThere.indexOf(getThere[i])) {
        info.innerHTML = "<p>" + getThere[i].line1 + "</p>";
        this.style.backgroundPositionX = getThere[i].x;
    } else {
        this.style.backgroundPositionX = "";
    }
   });
}

Ответы [ 2 ]

0 голосов
/ 13 декабря 2018
for(let i = 0; i < arr.length; i++) {
        arr[i].addEventListener("click", function() {
            if (arr.indexOf(this) == getThere.indexOf(getThere[i])) {
                info.innerHTML = "<p>" + getThere[i].line1 + "</p>";
                //To all tab of the options here are going to have to restore to its original state, and the option to change the current click
                //arr[i].style.backgroundPositionX = 0;
                this.style.backgroundPositionX = getThere[i].x;
            } else {
                this.style.backgroundPositionX = "";
            }
        });
    }
0 голосов
/ 13 декабря 2018

Здесь изменился ваш JS-код и работает JSFiddle https://jsfiddle.net/a8bjexLg/3/:

const info = document.getElementById("info");
const tab = document.getElementsByClassName("tab");
let el;
let arr = Array.prototype.slice.call(tab);


const getThere = [{
        line1: "By train....",
        x: "-44px"
    },
    {
        line1: "By car....",
        x: "-35px"
    },
    {
        line1: "By plane....",
        x: "-48px"
    }
];

for (let i = 0; i < arr.length; i++) {
    arr[i].addEventListener("click", function() {
        if (arr.indexOf(this) == getThere.indexOf(getThere[i])) {
            info.innerHTML = "<p>" + getThere[i].line1 + "</p>";
            this.style.backgroundPositionX = getThere[i].x;
        } else {
            this.style.backgroundPositionX = "";
        }


        resetSiblings(arr.indexOf(this));
    });
}

function resetSiblings(indexOfClickedElement) {
    for (let i = 0; i < arr.length; i++) {
        if (indexOfClickedElement !== i) {
            arr[i].style.backgroundPositionX = "";
        }
    }
}

Проблема заключалась в том, что вы предполагали, что событие onClick будет срабатывать для каждого элемента, но оно срабатывает только для элемента, который был в данный моментщелкнул.Я делаю простую модификацию вашего кода и добавил функцию, которая сбрасывает других братьев и сестер.

...