我正在尝试使用SetInterval重复执行一个缩小和扩大图像的功能,但是它没有抓住我的旗帜,因此它一直朝一个方向前进,而不是交替缩小和扩大。
function foo(toggle) {
let img = document.querySelector('.product-image')
if (img.style.width == "") { img.style.width = "0px"};
let width = parseInt(img.style.width.match(/\d+/g)[0])
if (toggle == false) {
width = width + 50;
img.style.width = width.toString() + "px"
img.style.transition = "all 2s"
toggle = true;
} else {
width = width - 50;
img.style.width = width.toString() + "px"
img.style.transition = "all 2s"
toggle = false;
}
}
let interval = setInterval(foo(false), 1000)
答案 0 :(得分:1)
由于您需要使用foo
或true
来调用false
,所以我认为您可能更喜欢递归setTimeout
而不是setInterval
:
function foo(toggle) {
const img = document.querySelector('.product-image');
img.style.width = img.style.width || "0px";
const currentWidth = parseInt(img.style.width.match(/\d+/g)[0])
const newWidth = toggle
? currentWidth + 50
: currentWidth - 50;
img.style.width = newWidth.toString() + "px"
img.style.transition = "all 2s"
setTimeout(foo.bind(null, !toggle), 1000);
}
foo(false)
<img class="product-image" src='https://upload.wikimedia.org/wikipedia/commons/9/9a/Random-image.jpg'/>
答案 1 :(得分:1)
您正在调用在每次调用中传递 false 值的函数。 您应该在最后一行中传递变量而不是硬编码值。 无论如何,您都可以解决此问题而无需将toggle值作为参数传递。 另一方面。您无需在if / else的每个块中重写前三行。
它看起来像这样:
let toggle = false;
function foo() {
let img = document.querySelector('.product-image')
if (img.style.width == "") { img.style.width = "0px"};
let width = parseInt(img.style.width.match(/\d+/g)[0])
if (!toggle) { // shorter for toggle == false
width += 50;
} else {
width -= 50;
}
img.style.width = width.toString() + "px"
img.style.transition = "all 2s"
toggle = !toggle; // inverts the boolean value of toggle
console.log(toggle);
}
/*
* pass the function without parentheses
* so you pass a reference to the function
* instead of its returning value
*/
let interval = setInterval( foo, 1000);
答案 2 :(得分:1)
toggle
设为全局变量,img
设置为全局变量,因此:
function foo() {
if (img.style.width == "") {
img.style.width = "0px";
}
let width = parseInt(img.style.width.match(/\d+/g)[0]);
if (toggle) {
width -= 50;
}
else {
width += 50;
}
img.style.width = width + "px";
toggle = !toggle;
}
const img = document.querySelector('.product-image');
let toggle = true;
img.style.transition = "all 2s";
let interval = setInterval(foo, 1000);