单击特定按钮更改div背景图像

问题描述 投票:0回答:4

我试图制作一个页面,其中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”。

有谁知道如何解决这个问题?

javascript click background-image
4个回答
0
投票

问题是你正在测试x.clicky.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?1511798933&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>

0
投票

你可能应该改变你的方式:

我会建议这样的事情:

        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


0
投票

你可以尝试这样的事情:

Array.from(document.querySelectorAll('input[type="button"]')).forEach(function(btn) {
  btn.addEventListener("click", photo);
})

function photo(e) {
  var id = e.target.getAttribute("id"),
    url = "none";
  switch (id) {
    case "one":
      url = "url('1.png')";
      break;
    case "two":
      url = "url('2.png')";
      break;
    case "three":
      url = "url('3.png')";
      break;
    case "four":
      url = "url('4.png')";
      break;
  }
  document.getElementById("photodiv").style.backgroundImage = url;
}
<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">

0
投票

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">`
© www.soinside.com 2019 - 2024. All rights reserved.