[英]How is it possible to change an img src using 'srcset' using JS, based on which onclick?
I'm trying to make a simple product page for t-shirts.我正在尝试为 T 恤制作一个简单的产品页面。 The user can press different colored buttons, which should activate a function to see which ID is being clicked.
用户可以按下不同颜色的按钮,这应该会激活一个功能来查看正在点击哪个 ID。 Then based on the ID, the img src is changed to represent the current image/color t-shirt.
然后根据 ID,将 img src 更改为表示当前图像/颜色的 T 恤。
I want to use the 'srcset' attribute in JS.我想在 JS 中使用 'srcset' 属性。
Using IF statements, I've been able to change the color of the t-shirt onclick - but no mater which option is clicked only the last color in the array is presented.使用 IF 语句,我已经能够在单击时更改 T 恤的颜色 - 但无论单击哪个选项,都只会显示数组中的最后一个颜色。
The issue is that it only changes the t-shirt color to one color, seeming to ignore the 'else if'.问题是它只将 T 恤颜色更改为一种颜色,似乎忽略了“否则如果”。
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>
What am I doing wrong?我究竟做错了什么?
If there's an easier way to do this using srcset/attribute manipulation in JS please don't hesitate to let me know.如果在 JS 中使用 srcset/attribute 操作有更简单的方法来做到这一点,请不要犹豫让我知道。 Just kindly tell me how your code works if it isn't beginner friendly.
如果您的代码不适合初学者,请告诉我您的代码是如何工作的。
Just pass a parameter in your code, that will do the work.只需在您的代码中传递一个参数,即可完成工作。
I've edited your code and just set a parameter on your onChange function.我已经编辑了你的代码,只是在你的 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>
You need to review the way you perform the test.您需要检查执行测试的方式。
The line of code if (tShirtObj.green.onclick) {
is actually checking if you have a onclick event associated.这行代码
if (tShirtObj.green.onclick) {
实际上是在检查您是否有关联的 onclick 事件。
You can find here a simplified exemple of the condition with a variable :您可以在此处找到带有变量的条件的简化示例:
let f = function() { alert('I am doing something'); }
if (f)
alert('I will be executed');
If you want more information on onclick .如果您想了解有关onclick 的更多信息。
The best solution for your problem is to use the event objects.您的问题的最佳解决方案是使用事件对象。 (e in this exemple)
(本例中的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
}
}
I think you could do it simpler我想你可以做得更简单
JS: 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: 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 is not for setting src with javascript. srcset 不是用于使用 javascript 设置 src。 https://www.w3schools.com/tags/att_source_srcset.asp check this for more information.
https://www.w3schools.com/tags/att_source_srcset.asp检查这个以获取更多信息。 But for what you are trying to do you.
但是对于你正在尝试做的事情。 maintain separate functions to do separate things.
维护不同的功能来做不同的事情。
<!--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">
then comes javascript然后是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/ https://jsfiddle.net/56q4ta3e/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.