如何根据哪个onclick使用JS使用'srcset'更改img src?

How is it possible to change an img src using 'srcset' using JS, based on which onclick?

我正在尝试制作一个简单的 T 恤产品页面。用户可以按不同颜色的按钮,这应该会激活一个功能来查看正在单击哪个 ID。然后根据ID,将img src改为代表当前的image/color t恤。

我想在JS中使用'srcset'属性

使用 IF 语句,我已经能够在单击时更改 T 恤的颜色 - 但无论单击哪个选项,都只显示数组中的最后一种颜色。

问题是它只将 T 恤颜色更改为一种颜色,似乎忽略了 'else if'。

var tShirtObj = {
    tShirt: document.getElementById('t-shirt'),
    green: document.getElementById('green'),
    blue: document.getElementById('blue'),
    gray: document.getElementById('gray'),
    black: document.getElementById('black'),
    yellow: document.getElementById('yellow')
};


// Function to check which ID's onclick is pressed to change the color.
function colorChange() {
    if (tShirtObj.green.onclick) {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035500.jpg" // green
    } else if (tShirtObj.blue.onclick) {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035400.jpg" // blue
    } else if (tShirtObj.gray.onclick) {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1118100.jpg" // gray
    } else if (tShirtObj.black.onclick) {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035200.jpg" // black
    } else if (tShirtObj.yellow.onclick) {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1012700.jpg" // yellow
    }
}
.card {
    margin: 0 auto;
}

.btn-red {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: red;
    cursor: pointer;
}

.btn-gray {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: gray;
    cursor: pointer;
}

.btn-green {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: rgb(117, 184, 117);
    cursor: pointer;
}

.btn-blue {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: blue;
    cursor: pointer;
}

.btn-yellow {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: yellow;
    cursor: pointer;
}

.btn-black {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: black;
    cursor: pointer;
}
<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <!-- Animate.CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
  <!-- Google Font -->
  <link href="https://fonts.googleapis.com/css?family=Nunito:200,300,400,700" rel="stylesheet">
  <!-- Animate CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
    integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <!-- Custom CSS -->
  <link rel="stylesheet" href="style.css">
  <!-- Custom Javascript -->
  <!-- <script src="script.js"></script> -->
  <title>JS SECTION</title>
</head>

<body>
  <div class="container text-center ">
    <h1>JAVASCRIPT CHANGE PRODUCT COLOR</h1>

    <h1 class="display-4">T-shirt</h1>

    <div class="card mt-5" style="width: 18rem;">
      <img src="https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1118100.jpg"
        class="card-img-top pt-3" alt=T-shirt id="t-shirt">
      <div class="card-body">
        <h5 class="card-title">T shirt, premium</h5>
        <p class="card-text">This premium T-shirt is made from the finest cotton in the world! Many sizes and colors!
        </p>
        <p><span>$</span>9.99,-</p>
        <a href="#" class="btn btn-success float-left mt-3">PURCHASE!</a>
        
        <div class="floating float-right">
          <button class="btn-gray" onclick="colorChange()" id="gray"></button>
          <button class="btn-red" onclick="colorChange()" id="red"></button>
          <button class="btn-yellow" onclick="colorChange()" id="yellow"></button>
          <div></div>
          <button class="btn-blue" onclick="colorChange()" id="blue"></button>
          <button class="btn-black" onclick="colorChange()" id="black"></button>
          <button class="btn-green" onclick="colorChange()" id="green"></button>
        </div>
        
      </div>
    </div>

  </div>

  <!-- Scripts -->
  <script src="script.js"></script>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
  </script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
    integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous">
  </script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
    integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous">
  </script>

</body>

</html>

Codepen

我做错了什么?

如果在 JS 中使用 srcset/attribute 操作有更简单的方法,请随时告诉我。如果您的代码对初学者不友好,请告诉我它是如何工作的。

您需要检查执行测试的方式。

代码行 if (tShirtObj.green.onclick) { 实际上是在检查您是否有关联的 onclick 事件。

您可以在此处找到带有变量的条件的简化示例:

let f = function() { alert('I am doing something'); }

if (f)
    alert('I will be executed');

如果您想了解有关 onclick 的更多信息。

您的问题的最佳解决方案是使用事件对象。 (本例中的 e)


function colorChange(e) {
    if (e.target.id == 'green') {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035500.jpg" // green
    } else if (e.target.id == 'blue') {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035400.jpg" // blue
    } else if (e.target.id == 'gray') {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1118100.jpg" // gray
    } else if (e.target.id == 'black') {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035200.jpg" // black
    } else if (e.target.id == 'yellow') {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1012700.jpg" // yellow
    }
}

我认为你可以做得更简单
JS:

let tShirt = document.getElementById('t-shirt');
let srcMap = new Map([
    ['green', 'https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035500.jpg'],
    ['blue', 'https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035400.jpg'],
    ['gray', 'https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1118100.jpg'],
    ['black', 'https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035200.jpg'],
    ['yellow', 'https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1012700.jpg'],
]);

function colorChange(btn) {
    let src = srcMap.get(btn.id);
    tShirt.srcset = src;
}

html:

<div class="floating float-right">
    <button class="btn-gray" onclick="colorChange(this)" id="gray"></button>
    <button class="btn-red" onclick="colorChange(this)" id="red"></button>
    <button class="btn-yellow" onclick="colorChange(this)" id="yellow"></button>
    <div></div>
    <button class="btn-blue" onclick="colorChange(this)" id="blue"></button>
    <button class="btn-black" onclick="colorChange(this)" id="black"></button>
    <button class="btn-green" onclick="colorChange(this)" id="green"></button>
</div>

srcset 不适用于使用 javascript 设置 src。 https://www.w3schools.com/tags/att_source_srcset.asp 检查此以获取更多信息。 但是对于你想做的事情。维护不同的功能来做不同的事情。

<!--buttons -->
<button class="btn-tshirt" data-myattribute="blue">blue</button>
<button class="btn-tshirt" data-myattribute="black">black</button>
<button class="btn-tshirt" data-myattribute="gray">gray</button>
<!-- the image -->
<img id="imageToChange" src="https://www.salomon.com/sites/default/files/products- 
 images/900x900/xa-tee-m__LC1035500.jpg" height="100" width="100">

然后是 javascript

//get all buttons
  var classname = document.getElementsByClassName("btn-tshirt");
 /*we maintain all images be careful here because in the key value pair here
  * the key should be used as a attribute for the image
  */
  const images ={
      blue:"https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035400.jpg",
      black:"https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035200.jpg",
      gray:"https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee- m__LC1118100.jpg"
             } 
   //add event listener to all the buttons
   Array.from(classname).forEach(function(element) {
        element.addEventListener('click', myFunction);
    }); 
  // the below function is called when the button is clicked
  function myFunction() {
   var attribute = this.getAttribute("data-myattribute");
   changeSrc(images[attribute])
    }
  //change the image src here
  function changeSrc(url) {
      let image=  document.getElementById("imageToChange")
       image.src=url
    }

https://jsfiddle.net/56q4ta3e/1/

只需在您的代码中传递一个参数即可完成工作。

我已经编辑了你的代码,只是在你的 onChange 函数上设置了一个参数。

var tShirtObj = {
    tShirt: document.getElementById('t-shirt'),
    green: document.getElementById('green'),
    blue: document.getElementById('blue'),
    gray: document.getElementById('gray'),
    black: document.getElementById('black'),
    yellow: document.getElementById('yellow')
};


// Function to check which ID's onclick is pressed to change the color.
function colorChange(a) {
    if (a=='green') {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035500.jpg" // green
    } else if (a=='blue') {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035400.jpg" // blue
    } else if (a=='gray') {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1118100.jpg" // gray
    } else if (a=='black') {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1035200.jpg" // black
    } else if (a=='yellow') {
        tShirtObj.tShirt.srcset = "https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1012700.jpg" // yellow
    }
}
.card {
    margin: 0 auto;
}

.btn-red {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: red;
    cursor: pointer;
}

.btn-gray {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: gray;
    cursor: pointer;
}

.btn-green {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: rgb(117, 184, 117);
    cursor: pointer;
}

.btn-blue {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: blue;
    cursor: pointer;
}

.btn-yellow {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: yellow;
    cursor: pointer;
}

.btn-black {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: black;
    cursor: pointer;
}
<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <!-- Animate.CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
  <!-- Google Font -->
  <link href="https://fonts.googleapis.com/css?family=Nunito:200,300,400,700" rel="stylesheet">
  <!-- Animate CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css">
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
    integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <!-- Custom CSS -->
  <link rel="stylesheet" href="style.css">
  <!-- Custom Javascript -->
  <!-- <script src="script.js"></script> -->
  <title>JS SECTION</title>
</head>

<body>
  <div class="container text-center ">
    <h1>JAVASCRIPT CHANGE PRODUCT COLOR</h1>

    <h1 class="display-4">T-shirt</h1>

    <div class="card mt-5" style="width: 18rem;">
      <img src="https://www.salomon.com/sites/default/files/products-images/900x900/xa-tee-m__LC1118100.jpg"
        class="card-img-top pt-3" alt=T-shirt id="t-shirt">
      <div class="card-body">
        <h5 class="card-title">T shirt, premium</h5>
        <p class="card-text">This premium T-shirt is made from the finest cotton in the world! Many sizes and colors!
        </p>
        <p><span>$</span>9.99,-</p>
        <a href="#" class="btn btn-success float-left mt-3">PURCHASE!</a>
        
        <div class="floating float-right">
          <button class="btn-gray" onclick="colorChange('gray')" id="gray"></button>
          <button class="btn-red" onclick="colorChange('gray')" id="red"></button>
          <button class="btn-yellow" onclick="colorChange('yellow')" id="yellow"></button>
          <div></div>
          <button class="btn-blue" onclick="colorChange('blue')" id="blue"></button>
          <button class="btn-black" onclick="colorChange('black')" id="black"></button>
          <button class="btn-green" onclick="colorChange('green')" id="green"></button>
        </div>
        
      </div>
    </div>

  </div>

  <!-- Scripts -->
  <script src="script.js"></script>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
  </script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
    integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous">
  </script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
    integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous">
  </script>

</body>

</html>