使用多个按钮和javascript更改图像

时间:2017-02-24 15:18:21

标签: javascript image button

我有来自另一个stackoverflow问题的代码,使用多个SELECT和javascript来改变图像:



function swapImage(){
    var image = document.getElementById("imageToSwap");
    var color = document.getElementById("colour").value;
    var size = document.getElementById("size").value;

    image.src = "img/" + size + "_" + color;
};

<img id="imageToSwap" src="img/red.png">

<select id="colour" onChange="swapImage()">
    <option value="red.png">Red</option>
    <option value="green.png">Green</option>
</select>

<select id="size" onChange="swapImage()">
    <option value="small">Small</option>
    <option value="large">Large</option>
</select>
&#13;
&#13;
&#13;

那么,如何将SELECT更改为BUTTON?

例如:

&#13;
&#13;
function swapImage(){
    var image = document.getElementById("imageToSwap");
    var color = document.getElementById("colour").value;
    var size = document.getElementById("size").value;

    image.src = "img/" + size + "_" + color;
};
&#13;
<img id="imageToSwap" src="img/red.png">

<div id="colour" onChange="swapImage()">
  <button value="red.png">Red</button>
  <button value="green.png">Green</button>
</div>

<div id="size" onChange="swapImage()">
  <button value="small">Small</button>
  <button value="large">Large</button>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

你可以像贝娄那样做。它工作正常,初学者也很明白。

var color = 'Red';
var size = 'Green';

function changeColor(newColor) {
    color = newColor;
    updateImage();
}

function changeSize(newSize) {
    size = newSize;
    updateImage();
}

function updateImage(){
    var image = document.getElementById("imageToSwap");
    image.src = "img/" + size + "_" + color;
};

<img id="imageToSwap" src="img/red.png">

<div>
  <button value="red.png" onClick="changeColor('Red')">Red</button>
  <button value="green.png" onClick="changeColor('Green')">Green</button>
</div>

<div>
  <button value="small" onClick="changeSize('Small')">Small</button>
  <button value="large" onClick="changeSize('Large')">Large</button>
</div>

答案 1 :(得分:0)

您可以通过按钮实现相同的功能

这里我调用每个按钮的函数onclick。这些按钮位于div内,其ID为coloursize。将id的属性作为颜色和大小更改

var color = 'red.png';//default values
var size = 'small';//default values

function swapImage(obj) {
  var image = document.getElementById("imageToSwap");


  if (obj.parentElement.getAttribute('id') == "colour") {
    color = obj.getAttribute('value')
  }
  if (obj.parentElement.getAttribute('id') == "size") {
    size = obj.getAttribute('value')
  }


  image.src = "img/" + size + "_" + color;
};
<img id="imageToSwap" src="img/red.png">

<div id="colour">
  <button value="red.png" onclick="swapImage(this)">Red</button>
  <button value="green.png" onclick="swapImage(this)">Green</button>
</div>

<div id="size">
  <button value="small" onclick="swapImage(this)">Small</button>
  <button value="large" onclick="swapImage(this)">Large</button>
</div>