gpt4 book ai didi

javascript - 使用 Array 在 javascript 中单击时更改图像

转载 作者:行者123 更新时间:2023-11-30 14:47:28 25 4
gpt4 key购买 nike

所以我有一个问题。现在我有一个代码,当我点击它时它会改变我的图像,这很棒。但我实际上需要它对不同的图像进行多次操作。我的结论:我需要一个数组。但是,我还没有成功地真正弄清楚如何使用此功能创建一个可用的。

我到处搜索并设法收集了一个代码,它做了一些类似但不完全相同的事情(比如用一个数组但用一个按钮改变图像)这个 JSfiddle 就是我正在谈论的那个,改变图像用按钮 https://jsfiddle.net/ffd7tmwy/1/

所以我尝试编辑它,但我失败了。这是我的尝试:

var change = document.getElementById('one');
var counter = 0;
var myPictures = [
"url(img/one_two.jpg"
];

function nextPic() {
counter += 1;
if (counter > myPictures.length -1) {
counter = 0;
}
change.src = myPictures[counter];
}

这是可以正常工作但没有数组或多张图片的:

$(".one").on("click", function() {
$(this).css("background-image", "url(img/one_two.jpg)");
});

这是另一个没用的..

var backgroundImg = new Array(); 
backgroundImage[0] = "url/one_two.jpg";

];

$(function() {
$('.one').on('click', function(){
$('.one').css('background-image', 'url(' + backgroundImg[0] + ')');
console.log(backgroundImg);
});

我希望有人能帮助我并解释我如何解决它。

谢谢!

最佳答案

根据有效的方法,看起来您只需要修改代码即可正确修改 background-image CSS 属性而不是 src 属性。这是您的代码,但已修改为执行此操作(以及不同的图像 URL):

var change = document.getElementById('one');
var counter = 0;
var myPictures = [
"https://picsum.photos/200/200?image=929",
"https://picsum.photos/200/200?image=735",
"https://picsum.photos/200/200?image=1063",
];

function nextPic() {
counter += 1;
if (counter > myPictures.length -1) {
counter = 0;
}
change.style.backgroundImage = "url(" + myPictures[counter] + ")";
}

// Here's how you can hookup the click event
change.addEventListener('click', nextPic);

// Load the first image
counter -= 1; // Do this so it starts at the first, not the second
nextPic();
#one {
width: 200px;
height: 200px;
border: solid 1px #000;
}
<div id="one"></div>

如果你想让它与多个元素一起工作,你可以创建一个函数来为你连接所有东西并跟踪哪个图像是可见的。

var myPictures = [
"https://picsum.photos/200/200?image=929",
"https://picsum.photos/200/200?image=735",
"https://picsum.photos/200/200?image=1063",
];

function createImageSwitcher(elementID) {
var element = document.getElementById(elementID);
var counter = 0;

function nextPic() {
counter += 1;
if (counter > myPictures.length - 1) {
counter = 0;
}
element.style.backgroundImage = "url(" + myPictures[counter] + ")";
}

element.addEventListener('click', nextPic);

// Load the first image
counter -= 1;
nextPic();
}

createImageSwitcher('one');
createImageSwitcher('two');
createImageSwitcher('three');
#one,
#two,
#three {
width: 200px;
height: 200px;
border: solid 1px #000;
}
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>

关于javascript - 使用 Array 在 javascript 中单击时更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48692211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com