#javascript #click #background-image
#javascript #нажмите #background-image
Вопрос:
Я пытаюсь создать страницу, на которой фоновое изображение элемента div меняется, как только я нажимаю кнопку.
document.getElementById("one").addEventListener("click", photo);
document.getElementById("two").addEventListener("click", photo);
document.getElementById("three").addEventListener("click", photo);
document.getElementById("four").addEventListener("click", photo);
function photo()
{
var photograf= document.getElementById("photodiv");
var x= document.getElementById("one");
var y= document.getElementById("two");
var z= document.getElementById("three");
var t= document.getElementById("four");
if (x.click) {photograf.style.backgroundImage= "url('1.png')";}
else if (y.click) {photograf.style.backgroundImage= "url('2.png')";}
else if (z.click) {photograf.style.backgroundImage= "url('3.png')";}
else if (t.click) {photograf.style.backgroundImage= "url('4.png')";}
else {photograf.style.backgroundImage= "none";
}}
div id="photodiv">
</div>
<input type="button" value="1" id="one">
<input type="button" value="2" id="two">
<input type="button" value="3" id="three">
<input type="button" value="4" id="four">
Проблема в том, что как только я пытаюсь нажать на кнопки, появляется единственная фотография «1.png», независимо от того, какую кнопку я нажимаю.
У кого-нибудь есть идея, как это можно решить?
Ответ №1:
Проблема в том, что вы тестируете x.click
, y.click
и т.д. который на самом деле не проверяет, какая кнопка была нажата, а вместо этого проверяет, есть ли у каждого элемента click
метод, что они все делают, но поскольку вы тестируете первый, x.click
и этот тест возвращает true
, это тот, который выполняется все время.
Код может быть немного упрощен без if/then
необходимости вообще. И все, что вам нужно сделать, чтобы добавить больше вариантов, это просто добавить еще одну кнопку и добавить новый путь к изображению в массив.
Смотрите комментарии ниже:
// Instead of setting up 4 separate event handlers that all point to the
// same callback function, we can use event delegation where we handle the
// event on an ancestor object of all the elements we care about
document.querySelector(".buttonContainer").addEventListener("click", photo);
// Store all the images in an array
var backgrounds = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/220px-SNice.svg.png",
"https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png",
"https://www.qualitylogoproducts.com/stress-balls/smileyface-squeezie-superextralarge-480745.jpg",
"https://cmkt-image-prd.global.ssl.fastly.net/0.1.0/ps/3647668/1160/1160/m1/fpnw/wm1/10837-royalty-free-rf-clipart-illustration-black-and-white-smiley-face-cartoon-character-vector-illustration-isolated-on-white-background-.jpg?1511798933amp;s=2e423029fc4d833fde26d36d8a064124"
];
// Get a reference to the output element
var picHolder = document.getElementById("photodiv");
// All event handling functions are automatically passed an argument
// that is a reference to the event object itself
function photo(event){
// Just set the background image based on the index of the button
// that got clicked within its parent and the corresponding index
// of the image in the array
// Get all the <input> elements
var buttons = document.querySelectorAll(".buttonContainer > input");
// Convert that node list into an array and get the index of the
// one that got clicked (event.target is the one that got clicked)
var index = (Array.prototype.slice.call(buttons)).indexOf(event.target);
// Set the background to the right image from the array
picHolder.style.backgroundImage = "url(" backgrounds[index] ")";
}
#photodiv { width:100px; height:100px; border:1px solid grey; background-size:cover; }
<!-- id's are not needed but wrapping all the buttons in a common ancestor will help -->
<div class="buttonContainer">
<input type="button" value="1">
<input type="button" value="2">
<input type="button" value="3">
<input type="button" value="4">
</div>
<div id="photodiv"></div>
Ответ №2:
вероятно, вам следует изменить способ, которым вы это делаете :
Я предложу что-то вроде этого:
document.getElementById("one").addEventListener("click", photo(1));
document.getElementById("two").addEventListener("click", photo(2));
document.getElementById("three").addEventListener("click", photo(3));
document.getElementById("four").addEventListener("click", photo(4));
function photo(x) {
var photograf= document.getElementById("photodiv");
switch (x) {
case 1:
photograf.style.backgroundImage= "url('1.png')";
break;
case 2:
//Statements executed when the
//result of expression matches value2
break;
default:
//Statements executed when none of
//the values match the value of the expression
break;
}
}
Источник :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Ответ №3:
function photo(e)
{
var photograf= document.getElementById("photodiv");
if(sanitize(e.target.value))
photograf.style.backgroundImage= `url('${e.target.value}.png')`;
}
div id="photodiv">
</div>
<input type="button" value="1" id="one">
<input type="button" value="2" id="two">
<input type="button" value="3" id="three">
<input type="button" value="4" id="four">`