我有3张图片(汽车,火车,飞机)。当我单击它们中的每个时,div信息都会获取旅行信息。每次单击图像时,我都希望像悬停时一样更改图像的状态。它可以做到,但是问题是一旦我单击一个新图像,旧图像就不会回到初始状态。请帮忙。
<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 = "";
}
});
}
答案 0 :(得分:1)
以下是您的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事件将针对每个元素触发,但仅针对当前单击的元素触发。我对您的代码进行了简单的修改,并添加了重置其他同级元素的功能。
答案 1 :(得分:0)
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 = "";
}
});
}